Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#if 0 as a define

I need a way to define a FLAGS_IF macro (or equivalent) such that

FLAGS_IF(expression)
<block_of_code>
FLAGS_ENDIF

when compiling in debug (e.g. with a specific compiler switch) compiles to

if (MyFunction(expression))
{
    <block_of_code>
}

whereas in release does not result in any instruction, just as it was like this

#if 0
    <block_of_code>
#endif

In my ignorance on the matter of C/C++ preprocessors I can't think of any naive way (since #define FLAGS_IF(x) #if 0 does not even compile) of doing this, can you help?

I need a solution that:

  • Does not get messed up if */ is present inside <block_of_code>
  • Is sure to generate 0 instructions in release even inside inline functions at any depth (I guess this excludes if (false){<block_of_code>} right?)
  • Is standard compliant if possible
like image 828
valerio Avatar asked Feb 09 '10 21:02

valerio


2 Answers

Macros are pretty evil, but there's nothing more evil than obfuscating control statements and blocks with macros. There is no good reason to write code like this. Just make it:

#ifdef DEBUG
  if (MyFunction(expression))
  {
    <block_of_code>
  }
#endif
like image 84
Hans Passant Avatar answered Sep 17 '22 16:09

Hans Passant


The following should do what you want:

#ifdef DEBUG
# define FLAGS_IF(x) if (MyFunction((x))) {
# define FLAGS_ENDIF }
#else
# define FLAGS_IF(x) if(0) {
# define FLAGS_ENDIF }
#endif

The if(0) should turn into no instructions, or at least it does so on most compilers.

Edit: Hasturkun commented that you don't really need the FLAGS_ENDIF, so you would instead write your code like this:

FLAGS_IF(expression) {
   <block_of_code>
}

with the follow macros:

#ifdef DEBUG
# define FLAGS_IF(x) if (MyFunction((x)))
#else
# define FLAGS_IF(x) if(0)
#endif
like image 25
bramp Avatar answered Sep 19 '22 16:09

bramp