Home > Software engineering >  Preprocessor directives in C
Preprocessor directives in C

Time:05-03

I have read several articles about how Preprocessor directives work in C . It's clear to me that Preprocessor directives are managed by the pre-processor before compilation phase. Let's consider this code:

#include <iostream>
#ifndef N
#define N 10
#endif 

int main(){
int v[N];
return 0;
}

The Pre-processor will elaborate the source code by performing text replacement, so this code during compilation phase would be equivalent to:

int main(){
int v[10];
return 0;
}

Now my question is: Can I define a Macro by setting its value equal to a function? It looks a bit weird to me but the answer is yes.

#include<iostream>
#include <limits>
#ifndef INT_MIN
#define INT_MIN std::numeric_limits<int>::min()
#endif
int get_max(){
    return 5;
}
#ifndef INT_MAX
#define INT_MAX get_max()
#endif

int main()
{
    std::cout << INT_MIN << " " << INT_MAX;
    return 0;
}   

Conceptually I'm not understanding why this code works, the pre-processor have to replace text before compilation phase, so how could a function be invoked (In this case get_max() function) ?

Functions invoking is a task managed by compiler? isn't it?

How could Pre-processor get access to std::numeric_limits::min()? This value is present inside the "limits" library, but if I understand correctly the libraries's inclusion is done by compiler.

CodePudding user response:

For the sake of illustration I removed the includes from your code:

#ifndef INT_MIN
#define INT_MIN 0
#endif
int get_max(){
    return 5;
}
#ifndef INT_MAX
#define INT_MAX get_max()
#endif

int main()
{
    return INT_MIN   INT_MAX;
}   

Then I invoked gcc with -E to see the output after preprocessing:

int get_max(){
    return 5;
}

int main()
{
    return 0   get_max();
}

This is the code that will get compiled. The preprocessor does not call the funciton. It merely replaces INT_MAX with get_max().

Live Demo

Can I define a Macro by setting its value equal to a function?

Thats not what you do. #define INT_MAX get_max() just tells the preprocessor to replace INT_MAX with get_max(). The preprocessor doen't know nor care if get_max() is a function call or something else.

  • Related