问题
I have only one file in my project called test.c; the code below does not compile if I do not define "TRUE". I use vc. I just want to understand the behavior. Please throw some light on this aspect.
#ifdef TRUE
static int a;
static int a = 1;
#else
static int a = 1;
static int a;
#endif
int main (void)
{
printf("%d\n", a);
return 0;
}
-----------------------
#ifdef TRUE // both ok
int a;
int a = 1;
#else // both ok
int a = 1;
int a;
#endif
int main (void)
{
printf("%d\n", a);
return 0;
}
回答1:
That is because you can not declare a variable after you have defined it. However you may define a variable after you declare it.
#ifdef TRUE
static int a; //Declaring variable a
static int a = 1; //define variable a
#else
static int a = 1; //define variable a
static int a; //Error! a is already defined so you can not declare it
#endif
回答2:
Apparently, the compiler does not let you redefine a variable that has been initialized..
来源:https://stackoverflow.com/questions/8417478/understanding-static-variables-declaration-initialization-in-c