Reputation: 8630
Consider the simple C program:
int a; // declaration
int a = 11; // initialization
int main(int argc, char* argv[]) {
int b; // declaration
b = 10; // assignment
If the initialization of a
were written without the data type, such as a = 11
, the compiler raises a warning. Why does the initialization of a
require a data type, when the declaration of a
already specifies its data type?
Upvotes: 7
Views: 147
Reputation: 43508
int a
at file scope is a "tentative" definition (because it lacks the initialising part). This means that a
can be defined again with a value at a later point.
A tentative definition may or may not act as a definition, depending on whether there is an actual external definition before or after it in the translation unit:
int a = 5; // defines a in the current translation unit with external linkage and a value of 5
int a; // tentative definition with no effect (a is already defined)
The other way around usually has more practical merit:
int a;
...
int a = 5;
The tentative definition could precede the actual definition, if, for example, the constant used to initialise it is not available at the first point.
Edit:
You seem to be confused that you are not able perform an assignment at file scope. A C program is allowed to have actual operations only within functions. At file scope, one may only define or declare variables, types and functions.
Upvotes: 3
Reputation: 418
I think this has something to do with the fact that you can't write instructions in the global scope. What it means is :
int a = 11;
Defines a variable. This tells the compiler to assign a static address to the variable, because it is global. The default (assignment) value is just an added bonus. Whereas :
a = 11;
Is an instruction, which is illegal.
Upvotes: 2
Reputation: 175
as your example:
int a; // <--- is a declaration
int a = 11; // <--- is reference to a const value
you can write code as this: int a;
int main() {
a = 11; // <--- simply no warning.
return 0;
}
That because a = 1; // <--- is a code statement int a = 1; // <--- is a ref to const value
In c, you may not write assignment out of function scope.
Upvotes: -2