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 ?
CodePudding user response:
Preprocessor definitions (aka Macros) are resolved during pre-compilation time, not during compilation time, and most certainly not during runtime, which seems to be what you're expecting.
Hence #if CHANGABLE_VALUE == 5 is replaced with #if var == 5 and then resolved as something which is false, so the actual code inside it is not even compiled (let alone executed).
CodePudding user response:
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");
}
