Pages

Thursday, June 09, 2005

C/C++: conditional compilation and #if 0

It is a common practice to use compiler's preprocessor for conditional compilation. Conditional compilation is useful when the application has platform specific code, and if it has to be supported on more than one platform.

eg.,
#ifdef SOLARIS
Solaris specific code here
#else if defined (WIN32)
Windows specific code
#endif

Besides platform specific code, conditional compilation is useful in many ways. It is extremely useful to disable large chunks of code in a program. If we need to keep some code only for future reference Or if we need to disable certain parts of the program tentatively, we can use conditional compilation. The trick is to use #if 0 .. #endif directive over the block of code to be disabled. As 0 is always "not true" (ie., !1; 1 is always true) in computer programming, the block of code within #if 0 .. #endif gets never compiled.

eg.,
#if 0
/* the following code will not be compiled */
int x = 100, y = 200, z = -1;
z = x + y;
..
#endif // #if 0

The compilation succeeds even though the code being disabled contain other conditionals as long as they are balanced. ie., entire conditionals with balanced #if and #endifs.

Also it helps, if the code has C style comments (/* .. */') embedded in it. It is a known fact that C comments do not nest, and results in a compilation error if we try to do so.

Technorati tag:

2 comments:

  1. Exactly what I was looking for. Thank you

    ReplyDelete
  2. Exactly what I was looking for too :)

    Thanks Mandalika

    ReplyDelete