Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding static variables declaration/initialization in C

Tags:

c

static

linkage

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; 
}
like image 209
caisp Avatar asked May 01 '26 16:05

caisp


1 Answers

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 
like image 56
Joe Avatar answered May 03 '26 05:05

Joe