根據 The C Programming Language, 4th Edition 一書 -
在 C 和較舊的 C 代碼中,您可以將字串文字分配給非常量 char*:
void f() { char* p = "Plato"; // error, but accepted in pre-C 11-standard code p[4] = 'e'; // error : assignment to const }接受這個任務顯然是不安全的。它曾經(并且現在)是細微錯誤的來源,因此如果某些舊代碼因此無法編譯,請不要抱怨太多。
它表明,上面的代碼應該出錯,但我收到了警告。
21:22:38 **** Incremental Build of configuration Debug for project study ****
Info: Internal Builder is used for build
g -std=c 0x -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\study.o" "..\\src\\study.cpp"
..\src\study.cpp: In function 'void f()':
..\src\study.cpp:10:13: warning: ISO C forbids converting a string constant to 'char*' [-Wwrite-strings]
uj5u.com熱心網友回復:
GCC 編譯器在默認情況下有些寬松,并允許一些擴展,例如隱式轉換字串的常量性。
很可能添加此擴展是為了保持與 C 的兼容性。
要禁用這些擴展,只需添加--pedantic-errors將使編譯器拒絕無效代碼的標志。
活生生的例子
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/368072.html
