在幫助手冊里查找const,可以找到以下的描述
1 Variables declared with the const type qualifier alone are stored in the memory area (data, idata, xdata, and so on) associated with their definition.
2 Variables you want to locate in ROM must be declared with the code memory type.
意思應該是:用CONST修飾修飾的變量放在RAM里了,但你不能改它。用CODE修飾符修飾的變量放在FLASH里了。
it is possible to assign the address of a const object (mask) to a non-const pointer (p) and subsequently use the pointer to change the const object. In this case, the compiler does generate code to write to the const object. The effects of this code is undefined and may or may not work as expected
可以用一個非COSNT的指針指向一個CONST變量,並且可以使用這個指針指向的變量。編譯器不會產生錯誤,但此時程序的運行結果是不可以預測的。
根據上面說的,const關鍵字在C51里的作用是弱的,所以基上應該用不到。不止是C51,一般的C也一樣。可以試一下,這個程序半個警告都沒有,但是運行結果是1。
#include <stdio.h>
#include <stdlib.h> int main(void) { const int a = 2; int *p; p = (int *)(&a); *p = 1; printf("%d\n", a); return 0; }
