The Curious Case of Preprocessors


What would be the output of the following code snippet:

#include <stdio.h>
#define V 1
int main()
{
  int Value = 1;
  #if V == Value
      printf("Hello world\n");
  #endif // V
  return 0;
}

If you guessed that the program will print “Hello world” you are wrong.

The reason being #if is a preprocessor directive and at the stage where preprocessor directives are evaluated or expanded, ‘int Value = 1’ has still not been processed and memory has not yet been allocated. This will happen only at the compilation stage and not the preprocessing stage.

So basically there is no meaning in V==Value and this will evaluate to false. So for this piece of code to work you will have to define even ‘Value’ with the #define statement.

Thanks to two of my colleagues Rakesh and Mitul for this interesting discsussion.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s