Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When should I use preprocessor directives over if statements

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading