如图所示,为什么还能编译过?
#include <stdio.h>
int aaa=0,bbb=0,ccc=0;
int aaa,bbb,ccc;
int aaa,bbb,ccc;
int aaa,bbb,ccc;
int main()
{
/* Write C code in this online editor and run it. */
printf("Hello, World! \n");
aaa = 10;
return 0;
}
如图所示,为什么还能编译过?
#include <stdio.h>
int aaa=0,bbb=0,ccc=0;
int aaa,bbb,ccc;
int aaa,bbb,ccc;
int aaa,bbb,ccc;
int main()
{
/* Write C code in this online editor and run it. */
printf("Hello, World! \n");
aaa = 10;
return 0;
}
代码中int aaa, bbb, ccc;
叫做暂定的定义,相当于声明。 这是为了兼容标准C语言之前的旧代码,那时候编译器把多个重复定义的全局变量合并成一个。
#include <stdio.h>
int aaa = 0, bbb = 0, ccc = 0; // external definitions
int aaa, bbb, ccc; // tentative definitions, act as declarations
int aaa, bbb, ccc; // tentative definitions, act as declarations
int aaa, bbb, ccc; // tentative definitions, act as declarations
int main()
{
/* Write C code in this online editor and run it. */
printf("Hello, World! \n");
aaa = 10;
return 0;
}
From https://en.cppreference.com/w/c/language/extern#Tentative_definitions
A tentative definition is an external declaration without an initializer, and either without a storage-class specifier or with the specifier static.
A tentative definition is a declaration that may or may not act as a definition. If an actual external definition is found earlier or later in the same translation unit, then the tentative definition just acts as a declaration.