Schafwolle
Schafwolle

Reputation: 531

One line #if statement

I have a config file with a lot of defines that are used to include modules during the complie time. In addition this means that I have to check very oft inside of the code for defines. Every check requires 3 lines is it possible to do this in one line.

#if FUNC_ENABLED
function_optional_call();
#endif

I'm looking for something like.

CALL(function_optional_call(),FUNC_ENABLED);

Is there a makro possible doing this or do I have to use the 3 line expression. I know its possbile to define a makro for every makro.

Skip function call if not defined

But is it possible to generate a generall makro.

Upvotes: 4

Views: 2797

Answers (3)

Quentin
Quentin

Reputation: 63124

It's pretty easy with the help of Boost.PP, in fact that's exactly what BOOST_PP_IF does:

#include <boost/preprocessor/if.hpp>

#define CALL(expr, cond) \
    BOOST_PP_IF(cond, expr,)

Every use of CALL expands to expr or nothing, depending on the value of cond.

Live on Coliru

Upvotes: 2

M.M
M.M

Reputation: 141554

Earlier on, have:

#if FUNC_ENABLED
#    define func_optional() real_func_name()
#else
#    define func_optional()
#endif

You could use some tricks in the second case to avoid problems caused by the semicolon, e.g. do {} while (0).

Upvotes: 1

Lundin
Lundin

Reputation: 213689

#if FUNC_ENABLED
function_optional_call();
#endif

is a canonical way of writing a compiler switch. It is clear, it is readable, every programmer understand what it does.

Now this code:

CALL(function_optional_call(),FUNC_ENABLED);

is completely mysterious. It is not clear what it is for, why there are macros... it doesn't even look like valid C.

Thus the first form is far superior, to the latter, which is just ugly, bad practice. So don't try to re-write the former into the latter.


If you worry about repeating the same line over and over, it would rather seem that the problem is an incorrect placement of the compiler switch. Put it inside the function instead. Or if you can't modify the function, make a wrapper.

Upvotes: 4

Related Questions