Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

Declaration of a static variable followed by redeclaration as extern and vice versa

$
0
0
#include <stdio.h>static int a;extern int a;int main(){    printf("Hello World");    printf("%d",a);    return 0;}

This C code compiles and runs fine.


#include <stdio.h>extern int a;static int a;int main(){ //static int a;    printf("Hello World");    printf("%d",a);    return 0;}

But this fails to compile and says:

error: static declaration of ‘a’ follows non-static declaration   11 | static int a;      |            ^main.c:10:12: note: previous declaration of ‘a’ with type ‘int’   10 | extern int a;

#include <stdio.h>static int a=9;int  a;int main(){ //static int a;    printf("Hello World");    printf("%d",a);    return 0;}

This code also gives an error:

error: non-static declaration of ‘a’ follows static declaration   14 |   int  a;note: previous definition of ‘a’ with type ‘int’   11 | static int a=9;

#include <stdio.h>static int a;int  a;int main(){     printf("Hello World");    printf("%d",a);    return 0;

Compilation error:

 error: non-static declaration of ‘a’ follows static declaration   14 |   int  a;      |        ^main.c:11:12: note: previous definition of ‘a’ with type ‘int’   11 | static int a=9;      |            ^

Please give why I am not getting any error when I am redeclaring with keyword extern and getting error when not using extern if the previous declaration is static.

By default file scope variables are treated as extern but why the error is occurring in the latter cases?

Please suggest according to C standards not machine dependent features.

What am I missing here ?


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>