| const |
| restrict |
| volatile |
宣告 const 的變數給定初值後,就不能更改其值,因此有如常數一般,將下例編譯會發生錯誤
#include <stdio.h>
int main(void)
{
const int n = 19;
printf("n = %d\n");
n = 33;
printf("n = %d\n");
return 0;
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:const_test.c
功能:示範 const 的錯誤使用
作者:張凱慶
時間:西元2010年4月 */編譯情況如下

n 為宣告成 const 的變數,其為 read-only ,也就是唯讀,只能讀,不能重新寫值進入的變數。
const 常用於函數間參數的傳遞,這樣限制被呼叫的函數無法更改參數的值,尤其在運用指標上,如下例
#include <stdio.h>
void printS(const char *);
int main(void)
{
char *saying = "While there is life, there is hope.";
printS(saying);
return 0;
}
void printS(const char *s)
{
while (*s != '\0') {
if (*s == ' ') {
printf("\n");
s++;
continue;
}
if (*s == '.') {
printf("\n");
break;
}
printf("%c", *s);
s++;
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:constptr.c
功能:示範將指標參數宣告為 const
作者:張凱慶
時間:西元2010年4月 */編譯後執行,如下

宣告成 volatile 的變數可能會被其他函數或外部事件所修改,因此要求編譯器每次使用此變數都需重新讀取。
restrict 只適用於指標,其為告訴編譯器,如果該指標所指向的變數被修改,就不可以直接或間接的被此指標以外的方式存取。
沒有留言:
張貼留言