在下面的代码中,为什么全局变量“x”的定义会显示警告“数据定义没有类型或存储类”,但对于局部变量“y”同样可以正常工作?我所做的一切对于每个变量,首先在一个语句中声明它们,然后在另一个语句中定义它们。它对一个变量工作正常但对另一个变量显示警告有什么区别?
#include<stdio.h>
int x;
x=303;
int main(void)
{
int y;
y=776 ;
printf("The value of x is %d,and of y is %d",x,y);
}
最佳答案
您正在以 C89 模式编译。
int x;
是x
的暂定定义。
x=303;
然后被解释为具有隐式类型 int
(int x = 303;
) 的变量 x
的定义。在 C99 或更高版本下,该代码将无法编译,因为“隐式 int
”规则已被废除,如果没有“隐式 int
”规则,第二行只能解释为一个语句,在文件范围内是不允许的。
使用 -std=c89 -Wall -Wextra -pedantic
编译(并添加 return 0;
到 main
),gcc 警告
redef.c:4:1: warning: data definition has no type or storage class [enabled by default]
redef.c:4:1: warning: type defaults to ‘int’ in declaration of ‘x’ [-Wimplicit-int]
关于c - 在 C 中,为什么在单独的语句中定义全局变量会引发警告,但对于局部变量却可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15734901/