51单片机全局变量或常量初始化需要注意的问题,参考代码如下:
int a = 12;
code int b = 13;
const int c = 14;
static int d = 15;
void main(void)
{
printf("a:%d, b:%d, c:%d, d:%d\n", a, b, c, d);
}
输入结果:
a:1, b:13, c:1, d:1
备注:
- 其中
a,c,d
的值都是不确定的(都没有初始化成功),只有b
的值是确定的,这个好像跟51单片机的内核架构有关。 - 用
const
修饰的变量放在RAM
里了,但你不能改它。用code
修饰的变量放在FLASH
里。 - const修饰的变量,通过一下方法能修改,编译器不报错。注意不要这样用。
#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;
}
//a的值被改为1