V

Avatar

C/C++ enable/disable code blocks with comments

Sometimes you’re writing code and need a quick way to enable/disable a section of code. That happens to me and most probably it happens to you too. I know of 2 ways to do this. You’ll need to change a character and compile the file, but that’s it. This does not allow you to change things in runtime, it’s all in compile time.

We can use C/C++ multiline comments /* */, to enable/disable blocks of code by changing a character. Check the following example:

/**/
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glDepthMask( GL_FALSE );
glEnable( GL_STENCIL_TEST );
/*/
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE );
glDepthMask( GL_TRUE );
glDisable( GL_DEPTH_TEST );
glDisable( GL_STENCIL_TEST );
/**/

To enable the second block -and disable the first- change /**/ into /*/ from the first line.
An alternative to the comment method is to use the #if #endif preprocessor directives. Using the same code example, if we wanted to enable the first block we’ll change it as follows:

#if 1
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glDepthMask( GL_FALSE );
glEnable( GL_STENCIL_TEST );
#else
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE );
glDepthMask( GL_TRUE );
glDisable( GL_DEPTH_TEST );
glDisable( GL_STENCIL_TEST );
#endif

To switch blocks, change #if 1 to #if 0. That’s pretty much it.

The example code above is not the best example at all, but take it as just that. An example. During your code sessions you’ll find better use for this i’m sure about that. Hope it helps.

No Comments, Comment or Ping

Comments are closed.