全局变量的值在我的代码中如何变化?

use*_*647 3 c global-variables

我在main函数之后再次声明了全局变量,但是它仍然会影响main函数。我知道C允许在第一次声明不初始化变量时再次声明全局变量(它将在c ++中不起作用)。如果我在main函数之后分配值,则它在c中仍然会出现两个警告,但在c ++中会给出错误。

我已经调试了代码,但没有成功int a=10;

#include <stdio.h>
#include <string.h>

int a;

int main()
{
    printf("%d",a);
    return 0;
}
/*a=10  works fine with following warnings in c.
        warning: data definition has no type or storage class
        warning: type defaults to 'int' in declaration of 'a' [-Wimplicit-int]|

        but c++ gives the following error
        error: 'a' does not name a type|
*/
int a=10;
Run Code Online (Sandbox Code Playgroud)

输出为10

Joh*_*ode 6

几件事:

  • 第一个int a;是暂定声明;第二个是暂定声明。第二个int a = 10;是定义性声明。

  • a是在文件作用域中声明的,因此它将具有static存储持续时间-这意味着将在程序启动时(main执行之前)保留它的存储并进行初始化,即使定义声明稍后在源代码中发生。

  • 较旧的C版本允许隐式int声明-如果出现的变量或函数调用没有声明,则假定它具有type int。C ++不支持隐式声明,因此会出现错误。