3

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; 
}
3
  • 1
    Try including the error message. We are not clairvoyant. Commented Dec 7, 2011 at 15:06
  • actually pasting the exact error message into your question is generally what you should be doing. Commented Dec 7, 2011 at 15:40
  • 'a' redefinition; different storage class Commented Dec 8, 2011 at 12:43

2 Answers 2

8

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 
Sign up to request clarification or add additional context in comments.

2 Comments

Well technically, you may define it after you declare it. :P But +1.
+1 for your comment, I was seeing variable and thinking struct.
-3

Apparently, the compiler does not let you redefine a variable that has been initialized..

1 Comment

you get in hells kitchen if you allow mulitple defines of the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.