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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With