Why can’t I assign values to global variables outside a function in C?

This is a definition of a global variable, with the optional initialisation to a specific value:

int i = 8;

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.)

i = 9;

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:

i = 9;
  • it is not inside a function, so it cannot be code
  • it looks like a variable definition, assuming that you mean it to be an int, i.e. the default
  • but relying on defaults is not a good idea, so warn about missing type and that the default is used
  • also, if it is a definition, then it is the second one for i, now that is really wrong, so show an error and fail the compiling
  • just to be helpful, mention where the first definition of i is

That is how to read the compiler output you have quoted.

Leave a Comment