Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

scope - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...