c語言中const關鍵字的常用用法
1.const關鍵字的意思
const 是 constant 的縮寫,恒定不變的、常數;恒量
它是定義隻讀變量的關鍵字,或者說 const 是定義常變量的關鍵字。
2.用法試例
2.1修飾普通變量
const int i = 1;<==> int const i = 1;
代碼段
#include<stdio.h>
int main(void){
const int i = 1;
i = 6;
printf("i=%d",i);
return 0;
}
gcc const.c
報錯:const.c: In function ‘main’:
const.c:6:4: error: assignment of read-only variable ‘i’
i = 6;
^
結論:const修飾普通變量,即不允許給它重新指派,即使是賦相同的值也不可以。代表隻讀變量
2.2修飾數組
#include<stdio.h>
int main(void){
const int arr[] = {2,2,2};
arr[2] = 3;
printf("i=%d",arr[2]);
return 0;
}
編譯報錯
const-array.c: In function ‘main’:
const-array.c:6:9: error: assignment of read-only location ‘arr[2]’
arr[2] = 3;
^
結論:const修飾數組,那麼相當于裡面的每個變量都被const修飾
2.3修飾指針
#include<stdio.h>
//1.const 在*前面
int main(void){
int a = 10;
int b = 20;
const int* p = &a;//<==> int const *p = &a;這兩個寫法一樣的意思
printf("a=%d",a);
printf("b=%d",b);
printf("p=%p",p);
//*p = 10;//這一行報錯
p = &b;
printf("p=%p",p);
printf("*p=%d",*p);
return 0;
}
//2.const 在*後面,
int main(void){
int a = 10;
int b = 20;
int* const p = &a;
printf("a=%d",a);
printf("b=%d",b);
printf("p=%p",p);
*p = 10;
//p = &b;//這一行報錯
printf("p=%p",p);
printf("*p=%d",*p);
return 0;
}
//3.
int main(void){
int a = 10;
int b = 20;
const int* const p = &a;
printf("a=%d",a);
printf("b=%d",b);
printf("p=%p",p);
//*p = 10;報錯
//p = &b;//這一行報錯
printf("p=%p",p);
printf("*p=%d",*p);
return 0;
}
結論:
1.const 在*前面,那麼該指針對應值不能變,意思就是該位址的值不變,但是p這個變量是可以變的,p可以重新指定為b的位址,人稱常量指針
2.const 在*後面,代表const修飾變量p,那麼p這個變量不能變,p又代表一個指針,是可以修改對應位址的值,人稱指針常量
3.兩個const這種情況代表p這個變量不能被修改,p對應位址的值也不能被修改
4.可以通過指針對第一種情況的值進行求改,但是在我這種環境編譯器會警告,可以變異通過,這樣子破壞了i的隻讀屬性
const.c:7:14: warning: initialization discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
int* p = &i;
5.特别的對下面這段代碼,指針數組(裡面全是指針的數組,是數組)
int a = 10;
int b = 20;
int c = 30;
const int* arr[] = {&a,&b};
//這種可以改變裡面的元素arr[0] = &c;,和一般的數組沒什麼差別,因為數組名本身就是常量不能被改變
int* const arr[] = {&a,&b};//這麼寫改變arr裡面的值就會編譯報錯
2.4修飾函數的參數
//如如,那麼表明a這個臨時變量不能被修改
int add(const int a){
//a = 10;報錯
}
3.總結
1.其他情況還未使用過
2.略,見上demo
3.有問題請指出商讨
本文測試環境
deppin系統15.11,gcc版本gcc version 6.3.0 20170516 (Debian 6.3.0-18+deb9u1)