Home > Enterprise >  When should I use preprocessor directives over if statements
When should I use preprocessor directives over if statements

Time:10-08

I am sorry if this sounds like a dumb question, I am learning C, and I was wondering: when should I prioritize this syntax, for example

#include <stdio.h>
#define ALIVE 1

int main(void) {
    #if ALIVE
    printf("Alive");
    #else
    printf("Unalived");
    #endif
}

Over this syntax (example):

#include <stdio.h>
#define ALIVE 1

int main(void) {
    if (ALIVE)
        printf("Alive");
    else
        printf("Unalived");
}

Thank you for spending time reading my question, I hope this isn't a dumb question and I wish you a nice day.

CodePudding user response:

For starters, and to see the main difference between the two programs you show, let's see how they will look after preprocessing.

The first one:

#include <stdio.h>
#define ALIVE 1

int main(void) {
    #if ALIVE
    printf("Alive");
    #else
    printf("Unalived");
    #endif
}

will expand to

#include <stdio.h>
#define ALIVE 1

int main(void) {
    printf("Alive");
}

The second one:

#include <stdio.h>
#define ALIVE 1

int main(void) {
    if (ALIVE)
        printf("Alive");
    else
        printf("Unalived");
}

will expand to:

#include <stdio.h>

int main(void) {
    if (1)
        printf("Alive");
    else
        printf("Unalived");
}

[Examples above skip the actual inclusion of the header file]

While this doesn't directly answer your question it can give hints to what using the preprocessor conditional compilation for.

The main use is to conditionally give the compiler different code depending on the macros. Mostly used for portability-issues, when creating programs that needs to be built for different systems (for example Linux and Windows).

When using the preprocessor to do conditional compilation, whole parts of the code, that would otherwise be invalid on the target system, could simply be omitted and the compiler won't even see it.

If you use the standard C if statement, then both branches of the condition must be valid code that the compiler can build.

CodePudding user response:

As a rule of thumb, you should always prefer if (... over #if and should only use #if where if will not work

  • when there's something in the if that is syntactically incorrect when the condition is false so it won't compile at all
  • when you need to do this at the global scope, where statements (like if) are not allowed

in your example, the if version is much better.

  • Related