Phil CK

Branch from Preprocessor

Last updated on

I see alot of code thats written like this

/* branch.c */

#include <stdio.h>

/* #define SOMETHING */

int
main() {

        #ifdef SOMETHING
        printf("Something\n");
        #else
        printf("No Something\n");
        #endif
        
        return 0;
};

Usually this is done to hide some extra feature, debug code or platform code. It can be nicer to just branch off the preprocessor instead.

That way the compiler will always evaluate both paths so if a particular branch goes stale you’ll know about it sooner.

/* branch.c */

#include <stdio.h>

/* toggle between 1 or zero */
#ifndef SOMETHING
#define SOMETHING 0
#endif

int
main() {

        if(SOMETHING) {
                printf("Something\n");
        } else {
                printf("No Something\n");
        }
        
        return 0;
};

Compile with something,

gcc branch.c -DSOMETHING=1 && ./a.out

outputs …

Something

Compile without something,

gcc branch.c && ./a.out

outputs …

No Something

There is no performance impact, the compiler is smart enough to notice the branch is constant and throw away the other branch.

Two things to consider however

  • Its not allways possible as sometimes are trying to hide platform differences.
  • MSVS will generate a warning by default.