Have no fear, the preprocessor is here

What is #ifndef, and why should anyone bother with it? These are two questions that will be answered in the coming lines.

The scope of this short article is to explain some basics about the preprocessor in C/C++ and give some examples of how to utilize this tool. Be aware that by no means is this written with good practice in mind.

Lets look at an example first, lets say we have a header file that declares a user defined struct, named date

#ifndef GUARD_mydate
#define GUARD_mydate

typedef struct date{
int yy;
int mm;
int dd;
};
#endif

Lets examine the code snippet, #ifndef, evaluates the expression to the right if it, in this case ‘GUARD_mydate’, if GUARD_mydate has not previously been defined, then this is evaluated as 1. #ifdef would evaluate to 0, following boolean logic.

The following line defines GUARD_mydate, so if the #ifndef is run again, we wont execute any code between #ifndef and #endif.

Wrapping a header file like this, ensures that even if there are multiple includes in the project, the declaration is only done once. Pretty neat right?

 

Okay, so this could be useful, you might think, and you have probally seen something similar when looking at someone elses code. But why is the preprocessor syntax different, why doesnt lines end with a ‘;’?

This is because the preprocessor does text substitution, lets illustrate that by an example

#include<stdio.h>
#define PI 3.1415
int main(){
int diameter = 5;
//circumference is 2*pi*r or pi*d
printf("a circle with diameter %dcm has"
"a circumference of %d\n", diamter, diameter*PI);

return 0;
}

Wherever PI occures in the code, it is substituted by whatever PI is defined as, hence if we end a line with ‘;’ when using the preprocessor, we would get compile time errors running the snippet above. Writing #define PI 3.1415; would result in printf(”….”, diameter, diameter*3.1415;); note the embedded semicolon.

At this point a discussion on #define vs const is merited, #define is global across the project, const even if it’s a global variable needs to be declared as external (locally) if used in other files.

Many coders advocate using const variables instead of #define, this is an issue that trickles down to readability.

For today we break here, next up on the preprocessor will be macros. Leave a comment below!