Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 927
Galaxy Avatar asked Jun 02 '18 21:06

Galaxy


1 Answers

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.

like image 133
Yunnosch Avatar answered Oct 07 '22 20:10

Yunnosch