I have this code:
#include <stdio.h>
extern int x;
void a() {
int x = 100;
printf("%d ",x );
x += 5;
}
void b() {
static int x = -10;
printf("%d ", x);
x += 5;
}
void c(){
printf("%d ", x);
x += 2;
}
int main() {
int x = 10;
a();
b();
c();
a();
b();
c();
printf("%d ", x);
getchar();
return 0;
}
int x = 0;
I was sure that the fact that extern in declared here, I will have a compilation error – but everything passed.
also , what is the meaning of extern when it’s inside the C file itself? shouldn’t it be in another file?
Is there a way to declare this variable in order for this not to compile?
The
externkeyword declares a variable, and tells the compiler there is a definition for it elsewhere. In the case of the posted code, the definition ofxoccurs aftermain(). If you remove theint x = 0;aftermain()the code will not build (it will compile but will fail to link due to undefined symbolx).externis commonly used to declare variables (or functions) in header files and have the definition in a separate source (.c) file to make the same variable available to multiple translation units (and avoid multiple definition errors):Note that the declaration of
xin functionsa(),b()andmain()hide the global variablex.