【學習總結】C語言的const到底修飾誰
阿新 • • 發佈:2018-12-18
不足之處還請指正。
const修飾的誰?
要在程式設計中多正確的使用const來使程式變得更加健壯。
《高質量C++/C程式設計指南》
const是修飾誰?
#include <stdio.h>
int main(int argc, const char * argv[])
{
const int num = 1; // 等價 int const num = 1;
num = 2; // ERROR!
int *p = # //WARNING!
*p = 30;
printf("*p = %d\n" , *p);
return 0;
}
ERROR:Cannot assign to variable 'num' with const-qualified type 'const int'
WARNING:Initializing 'int *' with an expression of type 'const int *' discards qualifiers
給出了警告,現在的編譯器都挺嚴格。
const int num = 1;
中的const修飾num是一個不可改變的變數,但是當我們用一個指標指向num,然後用指標改變值時卻可以。註釋掉ERROR那句執行結果為p = 30
#include <stdio.h>
int main(int argc, const char * argv[])
{
int num = 1;
const int *p = #
*p = 30; // ERROR!
printf("*p = %d\n", *p);
return 0;
}
ERROR:Read-only variable is not assignable
const int *p = #
中const修飾的是*p,也就是num,這句話的意思就是不能通過p來修改變數num的值
int const *p = #
是等價的,都是修飾*p。
int main(int argc, const char * argv[])
{
int num = 1;
int test = 20;
int * const p = #
*p = 30;
p = &test; // ERROR!
printf("*p = %d\n", *p);
return 0;
}
ERROR:Cannot assign to variable 'p' with const-qualified type 'int *const'
int * const p = #
中的const修飾的是指標p,也就是p裡的值是不可以改變的,不可以改變指標的指向。