我从一本关于暂定定义的书上看到,
A tentative definition is any external data declaration that has no storage class specifier and no initializer. A tentative definition becomes a full definition if the end of the translation unit is reached and no definition has appeared with an initializer for the identifier
请解释以上语句的含义。 另外,声明和定义之间的区别?由于这个,我混淆了。 :( 为什么这个程序不报错:
#include <stdio.h>
int a; //Tentative definition
int a; //similarly this declaration too.
int main() //not getting any error with this code why its so?
{
printf("hi");
}
此外,这段代码有什么问题:
#include<stdio.h>
printf("Hi");
int main(void){
return 0;
}
最佳答案
变量声明说,“程序中有一个具有以下名称和类型的变量”。
变量定义说,“亲爱的编译器先生,请立即为具有以下名称和类型的变量分配内存。”
所以同一个变量可以有多个声明,但应该只有一个定义。
在 C 中,纯声明(也不是定义)以关键字 extern
开头。因此,由于您在第一个示例中没有 this 关键字,所以您有两个定义。从表面上看,这似乎是一个问题(实际上是 C++ 中的一个错误),但是 C 有一个特殊的“暂定定义”规则,允许在同一个翻译单元中对同一个变量进行多个定义,只要它们都是匹配并且至多有一个初始化器。 C 编译器在后台将所有暂定定义合并为一个定义。
您是否尝试过初始化这两个定义,如下所示:
int a = 1;
int a = 2;
那么你就会出错。
你的第二个问题更直接。在 C 中,您根本无法在函数体之外拥有可执行语句。这是不允许的。想一想:如果允许的话,您希望它什么时候运行?
关于c - 关于暂定定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58589572/