squeevee squeevee - 20 days ago 5
C Question

c/c++ using else instead of if not

Encountered a bit of weird-looking code and it got me wondering if there's any practical application to it, or if it's just a random oddity.

The code essentially looks like this:

#ifdef PREPROCESSOR_CONDITION
if (runtime_condition) {
} else
#endif
{
//expression
}


I included the macro bit, though I doubt it has any bearing. There's no code that runs when runtime_condition is true, only the else block. I figure this ought to be completely identical to using if(!runtime_condition) and no else block (which would have been more straightforward), but maybe there's some kind of compiler-optimizey thing happening?

Or, you know, it could be that there used to be something in the if block that got deleted and nobody bothered to change the expression.

Answer

The "macro bit" is significant.

Consider what happens if the programmer mistakenly changes the snippet to

#ifdef PREPROCESSOR_CONDITION
if (runtime_condition)
{
}
else
#endif
{
    //expression
}
else
{
    // another expression
}

This will result in a compilation error, regardless of whether PREPROCESSOR_CONDITION is defined or not.

With your change, viz;

#ifdef PREPROCESSOR_CONDITION
if (!runtime_condition)
#endif
{
    //expression
}
else
{
    // another expression
}

it will compile if PREPROCESSOR_CONDITION is defined, but fail if it is not defined.

If the programmer who adds the else only attempts compilation in conditions with PREPROCESSOR_CONDITION defined, no problem will be found. There will then be a latent defect in the code, that will not be exposed until the code is compiled with PREPROCESSOR_CONDITION undefined.

This may seem minor in a single code snippet, but compilation errors occurring by surprise (e.g. code breaking in unexpected places) is a significant productivity concern if it occurs in larger projects.