我是“C”的新手,我试图通过练习“C”程序来理解“C”编程的细微差别。
我知道在 'C' 中可以在一个语句中声明属于同一数据类型的多个变量,如下所示:
int x, y, z;
我试图在一个语句中声明和定义属于同一数据类型的多个变量,如下所示:
#include <stdio.h>
int main() {
int x = y = z = 50;
printf("%d", x + y + z);
return 0;
}
当我尝试编译上面的代码时,出现以下错误:
prog.c: In function ‘main’:
prog.c:4:11: error: ‘y’ undeclared (first use in this function)
4 | int x = y = z = 50;
| ^
prog.c:4:11: note: each undeclared identifier is reported only once for each function it appears in
prog.c:4:15: error: ‘z’ undeclared (first use in this function)
4 | int x = y = z = 50;
| ^
我不明白为什么不能在单个语句中将属于同一数据类型的多个变量初始化为相同的值,而可以声明属于同一数据类型的多个变量。
我也不明白注释的实际含义每个未声明的标识符对于它出现在每个函数中只报告一次以及为什么会出现?
有人请用清晰的语言向我解释这些事情。
不过,当我尝试下面的代码时,我分别为变量声明和定义创建了两个语句,一切都运行顺利。为什么会这样?
#include <stdio.h>
int main() {
int x, y, z;
x = y = z = 50;
printf("%d", x + y + z);
return 0;
}
并得到低于预期的输出:
150