C preprocessor with if statement

I have the following macro:

#define IF_TRACE_ENABLED(level) if (IsTraceEnabled(level)) 

The user code should look like this:

 IF_TRACE_ENABLED(LEVEL1) { ... some very smart code } 

The emphasis here is on braces - I want to prevent the β€œif” from the macro in order to β€œeat” another code:

 if (...) IF_TRACE_ENABLED(LEVEL1) printf(....); else bla bla bla 

In this example, IF_TRACE_ENABLED "eating" else block.

Is there a way to prevent user code from compiling without curly brakes, or are there others to define a macro for security?

+6
macros c-preprocessor
source share
3 answers

This does not force the macro user to use curly braces, but it will prevent the else clause from being inadvertently used:

 #define IF_TRACE_ENABLED(level) if (!IsTraceEnabled(level)) {} else 

Side note: the brackets around printf() in the second example question would not fix the problem - else associated with bla bla bla will still be attached to the if in the macro.

+11
source share

You can try the following:

 #define IF_TRACE_ENABLED(level) do { if(IsTraceEnabled(level)) { #define END_TRACE_ENABLED } } while(0); 

I don’t think there is a way to β€œprovide” good syntax just from the first line of the macro. You will need to use two.

EDIT

I added an extra macro inside the macro to avoid any ambiguity.

In response to a comment, this macro is intended to be used as follows:

 IF_TRACE_ENABLED(LEVEL1) printf("Trace\n"); END_TRACE_ENABLED 

Not as a statement. For the record, I believe this is an abuse of the preprocessor, and no one should do this at all. What's wrong, just by writing it, enclosed in brackets with #ifdef DEBUG if necessary.

+2
source share

This should work, but you should also pass the contents of the if block as an argument to the macro:

 #define IF_TRACE_ENABLED(level,content) { if (IsTraceEnabled(level)) {content} } 
0
source share

All Articles