關於 const 常數與指標賦值的問題
測試環境:
$ gcc --version gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 Copyright (C) 2011 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
源碼:
#include <stdio.h>
int main(int argc, const char *argv[])
{
const int i = 1;
int *p;
p = &i;
*p = 2;
printf("%d\n", i);
printf("%d\n", *p);
return 0;
}
這段程式有點意思:i 被宣告為 const int,卻拿它的位址去賦值給 int *,然後透過 p 改掉內容。用 gcc 編譯時只會跳警告,程式照樣跑得出來;但若改用 g++ 編譯,直接就編譯不通過。
原因在於 C 語言對 const 的檢查相對寬鬆,把 const int * 轉成 int * 只是丟棄限定符,編譯器給個警告便放過;C++ 則把這種丟棄 const 限定視為錯誤。這個小例子正好說明:果然 C++ 的程式碼檢查更嚴格,跨語言移植時這類地方最容易踩雷。