In C,why is definition of a global variable in a separate statement raising warning,but is OK for a local variable?

In the following code, why does the definition of the global variable "x" show the warning "data definition has no type or storage class" but the same thing works fine for the local variable "y"?All I am doing for each variable is first declare them in one statement and then define them in another statement.What is the difference that it works fine for one but shows warning for the other?

    #include<stdio.h>

      int x;
      x=303;

     int main(void)
      {
        int y;
        y=776 ;

        printf("The value of x is %d,and of y is %d",x,y);
      }

Upvotes: 2

Views: 502

Answers (3)

Daniel Fischer
Daniel Fischer

Reputation: 183878

You're compiling in C89 mode.

  int x;

is a tentative definition of x.

  x=303;

is then interpreted as a definiton of the variable x with implicit type int (int x = 303;). Under C99 or later, that code would not compile since the "implicit int" rule was abolished and without the "implicit int" rule, the second line could only be interpreted as a statement, which is not allowed at file scope.

Compiling with -std=c89 -Wall -Wextra -pedantic (and adding a return 0; to main), gcc warns

redef.c:4:1: warning: data definition has no type or storage class [enabled by default]
redef.c:4:1: warning: type defaults to ‘int’ in declaration of ‘x’ [-Wimplicit-int]

Upvotes: 6

templatetypedef
templatetypedef

Reputation: 372784

The reason for this is that these two lines:

  int x;
  x = 303;

Consist of a declaration statement (int x;) and an expression used as a statement (x = 303;). The C programming language only allows for declarations and definitions at the level of global scope and disallows expressions at global scope. However, both declaration statements and expression statements are legal inside of C functions.

One intuitive way to think about this is the following: when would the code x = 303; be executed at global scope? Imagine that we had this program:

int x = 1;

void myFunction() {
    printf("%d\n", x);
}

x = 303;

Here, what value of x would myFunction see? Would it see the value 1, or would it see the value 303?

On the other hand, if we have

void myFunction() {
    int x;
    x = 303;
    printf("%d\n", x);
}

It is a bit more clear that we are supposed to execute these statements in order, so 303 would be printed.

Hope this helps!

Upvotes: 3

&#201;tienne
&#201;tienne

Reputation: 4984

You can not execute code outside of any function/block. x=303; is not valid in the position where you wrote it.

In this precise case (global scope), you can only initialize the variable directly with int x=303.

Upvotes: 1

Related Questions