Suppose I have a global variable, and I want to assign another variable to it. I've found out that you can assign another value to a global variable inside a function:
int i = 8;
int main(void)
{
i = 9; /* Modifies i */
return 0;
}
However, assignment of the global variable outside of a function does not work!
int i = 8;
i = 9; /* Compiler error */
int main(void)
{
return 0;
}
I get the following error message:
warning: data definition has no type or storage class
warning: type defaults to 'int' in declaration of 'i'
error: redefinition of 'i'
note: previous definition of 'i' was here
int i = 8;
^
Why is this happening?
This is a definition of a global variable, with the optional initialisation to a specific value:
Note that it is not code which gets ever executed, the variable will just be set up to initially contain the 8. Either consider it "magic" (a helpful model for many things not really defined by the standard) or think of tables with values being copied to memory locations before any code is executed.
This is a piece of code which has no "frame" in which it is executed.
(Or you intend it to be. The compiler is of other opinion, see below.)
There is no function containing it. It is not clear when it should be executed. That is what the compiler does not like.
In C, all code has to be inside a function and will only be executed if that function is called, e.g. from
main()
.Other language, mostly those which execute "scripts" by interpreting them (instead of code being turned into executeables, e.g. by a compiler) allow to have code anywhere. C is different.
The compiler sees this differently:
int
, i.e. the defaulti
, now that is really wrong, so show an error and fail the compilingi
isThat is how to read the compiler output you have quoted.