1

I was trying to compile this small code. But it seems, I see a wrong result. Any idea, where am I going wrong?

int a=2,b=3;
#if a==b
    printf("\nboth are equal.\n");   
#endif

Output:

both are equal.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Shivendra Mishra
  • 638
  • 4
  • 25

1 Answers1

11

The preprocessor works at preprocessing-time, which deals with preprocessor directives like #include, #define, #if-#else-#endif.
And the C code like int a=2,b=3; is parsed and compiled after that at compile-time, so you're not supposed to test like this.

Actually the symbol a and b, when being processed by the preprocessor, shall be empty if you didn't defined them previously. That's why a==b holds true.

EDITED:

Here are some valid examples:

int a = 2;
int b = 3;
// To test at runtime
if (a == b)
    puts("They are equal!");

#define A 2
#define B 3

// To test at preprocessing time
#if A==B
// This message is printed at runtime
puts("They are equal!");
#endif

// To test at preprocessing time
#if A==B
// This message is printed at preprocess-time
#error "They are equal!"
#endif
Community
  • 1
  • 1
starrify
  • 14,307
  • 5
  • 33
  • 50