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.

Advertisements

About vineethkartha

Hi, I am Vineeth Kartha, I hold a Masters degree in Embedded Systems from BITS Pilani, Goa Campus. I currently work as a Software Developer. I am A free software promoter and electronics hobbyist. In my free time I do a little bit of birding and Wildlife photography. I love travelling, reading and blogging.

Posted on January 11, 2017, in Technical. Bookmark the permalink. Leave a comment.

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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: