Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an 'if' condition that compiles only when DEBUG is #defined?

Tags:

c++

macros

I need some help in writing a macro for 'if-condition' which compiles only when a DEBUG flag is defined by the #define directive.

Here is an example which illustrates what I want. first piece of code shows the usual way of writing an if condition with a #ifdef.

#ifdef DEBUG
if( rv == false )
{
     string errorStr = "error in return value" ;
     cout << errorStr << endl ;
     throw( Exception(errorStr) ) ;
}

I want to write it in a way similar as below:

DEBUG_IF( rv==false )
{
     same code as above
}

It seems to be simple but I am having trouble defining a macro which can do this. If someone has experienced this before, kindly help.

Thanks.

like image 924
And Or Avatar asked Dec 17 '22 23:12

And Or


1 Answers

Try:

#ifdef DEBUG
  #define DEBUG_IF(x) if(x)
#else
  #define DEBUG_IF(x) if(false)
#endif

Now this won't be exactly the same as what you have right now, because when using this method, the code inside the if block still gets compiled, although it will never be run when DEBUG is not defined, and will probably be optimized out. In contrast, with your original example, the code is eliminated by the preprocessor and is never even compiled.

like image 79
Tyler McHenry Avatar answered Dec 19 '22 12:12

Tyler McHenry