'Macro Value Changes

I need to explain for the MACRO define and if else conditions.

When I using the below function I get CHANGE value to 5

#include <stdio.h>

#define CHANGE var
int var;
int main()
{
    var = 5;
    printf("%d",CHANGE);

}

Output: 5

But if I use like this:

#include <stdio.h>

#define CHANGABLE_VALUE var
int var;
int main()
{
    var = 5;
    #if CHANGABLE_VALUE == 5
    printf("%d",CHANGABLE_VALUE);
    #else
    printf("There is no value");
    #endif



}

Output: There is no value

Why the #if statements not working ?

c


Solution 1:[1]

There is a big difference between an #if preprocessor directive and a standard if statement. The preprocessor directive is evaluated before the code is actually compiled, whereas a standard if statement is evaluated at run-time.

Since

#if CHANGABLE_VALUE == 5

is false, the preprocessor will not include the line

printf("%d",CHANGABLE_VALUE);

in the code to be compiled. It will only include the #else part of the code, which is

printf("There is no value");

So, after the preprocessor phase is finished, your code will effectively look like this:

#include <stdio.h>

int var;
int main()
{
    var = 5;
    printf("There is no value");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andreas Wenzel