Difference between "defining" and "declaring" [duplicate]
Possible Duplicate:
What is the difference between a definition and a declaration?
I am trying to thoroughly understand "defining" and "decl开发者_如何学编程aring" in C.
I believe x
here is defined, since external variables are automatically initialized to 0, and something that's declared and initialized is defined. Is that accurate?
int x;
main() {}
According to one x
in this case is a definition, but why? It is not being initialized...
int print_hello()
{
int x;
}
Declaring is telling the compiler that there's a variable out there that looks like this.
Defining is telling the compiler that this is a variable.
One refers to the existence of a thing, the other is the thing.
In your example, the scope is what makes the difference. Declarations are made in a file scope, but in a block scope it is not possible to declare anything; therefore, the second example is a definition; because, there is nothing left to do with the int x;
.
That makes the first example (in the file scope) a declaration that some int x;
exists. To covert it from a declaration, you need to specify that a value is assigned to it, forcing the memory allocation. Like so: int x = 0;
C and C++ are very scope sensitive when it is analyzing constructs.
"Define" does not mean "initialized." It means something is created, rather than just referenced.
A definition allocates but does not necessarily initialize memory. This can lead to fun debugging.
Declaration introduces a name in a TU. Definition instantiates/allocates storage for that name.
int x; //definition,also a declaration. Every definition is a declaration.
int main(){}
精彩评论