问题:
c
//为什么下面这个程序可以运行
#include <REGX52.H>
#include "LCD1602.h"
#include "Delay.h"
unsigned int result = 0;
void main(){
LCD_Init();
while(1){
LCD_ShowNum(1,1,result,3);
Delay(200);
result++;
};
}
//但是这样会报错:
#include <REGX52.H>
#include "LCD1602.h"
#include "Delay.h"
void main(){
LCD_Init();
unsigned int result = 0;
while(1){
LCD_ShowNum(1,1,result,3);
Delay(200);
result++;
};
}
这两个程序的差异在于变量 result
的作用域和C语言的语法标准限制:
第一个程序(正常运行)
c
unsigned int result = 0; // 全局变量
void main() {
LCD_Init();
while(1) {
// 使用 result
result++;
};
}
- 全局变量 :
result
声明在全局作用域,生命周期覆盖整个程序运行,可在main
函数中正常读写。
第二个程序(报错)
c
void main() {
LCD_Init();
unsigned int result = 0; // 局部变量,声明在语句之后
while(1) {
// 使用 result
result++;
};
}
- 局部变量声明位置问题 :在C89/C90标准中,所有局部变量必须在函数或代码块的开头 声明(即在任何执行语句之前)。此代码中,
result
的声明位于LCD_Init()
调用之后,违反了这一规则,导致编译错误。
根本原因
- C语言标准兼容性:编译器(如Keil的默认配置)可能遵循C89标准,要求局部变量声明集中在代码块开头。C99及之后的标准允许在代码任意位置声明变量,但部分嵌入式编译器默认使用C89模式。
解决方案
将局部变量声明移至函数体开头:
c
void main() {
unsigned int result = 0; // 符合C89规则
LCD_Init();
while(1) {
// 使用 result
result++;
};
}
总结
第二个程序因违反C89的变量声明位置规则而报错,修正声明位置即可解决。全局变量不受此限制,因而第一个程序能正常运行。