Possible Duplicate:
What is the difference between a definition and a declaration?
I am trying to thoroughly understand "defining" and "declaring" 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;
}
Declaration means that variable is only declared and memory is allocated, but no value is set. However, definition means the variables has been initialized. The same works for variables, arrays, collections, etc.
Declaration vs Definition: In SummaryA declaration provides basic attributes of a symbol: its type and its name. A definition provides all of the details of that symbol--if it's a function, what it does; if it's a class, what fields and methods it has; if it's a variable, where that variable is stored.
Like a class, a method definition has two major parts: the method declaration and the method body. The method declaration defines all the method's attributes, such as access level, return type, name, and arguments, as shown in the following figure. The method body is where all the action takes place.
Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it. Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With