Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

c - About Tentative definition

I read from a book about tentative defination that,

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

Please explain what the above statement means. Also, the difference between Declaration and Definition? I got mixed up due to this. :( And why doesn't this program give an error:

#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");
} 

Also, what is wrong with this code:

#include<stdio.h>
printf("Hi");
int main(void){
    return 0;
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A variable declaration says, "there is a variable with the following name and type in the program".

A variable definition says, "Dear Mr. Compiler, please allocate memory for a variable with the following name and type now."

So there can be multiple declarations for the same variable, but there should be only one definition.

In C, pure declarations (that are not also definitions) are preceded with the keyword extern. So, since you do not have this keyword in your first example, what you have is two definitions. On its face, this would seem to be a problem (and is in fact an error in C++), but C has a special "tentative definition" rule which allows multiple definitions for the same variable in the same translation unit so long as they all match and at most one has an initializer. The C compiler, behind the scenes, combines all of the tentative definitions into a single definition.

Had you attempted to initialize both definitions, like this:

int a = 1;
int a = 2;

Then you would have had an error.

Your second question is more straightforward. In C, you simply cannot have executable statements outside of the body of a function. It's just not allowed. Think about it: when would you expect it to run if it were allowed?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...