Spacebrain
Spacebrain

Reputation: 97

Why using if statements in preprocessor defines?

When exploring a source package, I discovered that some if statements were defined by preprocessor directives and then used in the code like the example below:

#ifdef _WIN32
    #define OSisWindows() true
    #define OSisLinux() false
#elif defined(__linux__)
    #define OSisLinux() true
    #define OSisWindows() false
#endif

if ( OSisWindows() )
{
// do something
}

if ( OSisLinux() )
{
// do something else
}

Is there a difference between using this and simple defines like _WIN32 or __linux__ ?

Upvotes: 1

Views: 223

Answers (4)

utnapistim
utnapistim

Reputation: 27365

Is there a difference between using this and simple defines like _WIN32 or linux ?

No, this is simple macro abuse.

Upvotes: 0

ma0ho
ma0ho

Reputation: 633

In addition to what's already been written it's another layer of abstraction. If for example the syntax for _WIN32 changes or you want to explicitly compile for windows without relying on the flag, you'd have to change your complete code in case you would have used _WIN32 directly. In this case you could just change the preprocessor directives.

Upvotes: 1

ouah
ouah

Reputation: 145829

Assuming the macros are defined, the advantage of using an if..else statement over an #if .. #else directive is all code paths are compiled in the first case so if there are compile errors the compiler is able to see them in all the code paths. Of course this isn't always possible as some code paths may be platform dependent code.

Upvotes: 3

mark
mark

Reputation: 5469

Well, you can't use a macro directly in your code like:

if ( _WIN32 ) {
    ...
}

on linux for example because it isn't defined so they are simply mapping the macro to a boolean expression.

In in end, it's really a style decision though... they could have certainly done:

#ifdef _WIN32
    ...
#endif

Upvotes: 4

Related Questions