code是KEIL C51 扩展的关键字,用code修饰的变量将会被放到CODE区里。但C语里的const关键字好像也有定义不能改变的变量的功能,这两个关键字有什么区别呢? 在帮助手册里查找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; }