I have a fundamental question regarding the C preprocessor constant evaluation and I would like some help in understanding if the preprocessor helps in optimizing the code in a situation like this. I understand that the preprocessor merely "replaces text" in the code. By that rule, even constant expressions get replaced in the code. For instance, the below code:
#include <stdio.h>
#define MY_NUM 2+2*2
int main()
{
int a = 6/MY_NUM;
printf("a: %d\n", a);
return 0;
}
The value of a
comes to 7. This is because the preprocessed code looks something like this:
int main()
{
int a = 6/2+2*2;
printf("a: %d\n", a);
return 0;
}
I can see that MY_NUM
did not evaluate to 6 before the compilation kicks in. Of course the compiler then optimizes the code by evaluating the value of a
at compile time.
I am not sure if preprocessor constant folding happens or not or if it is even possible. Or is there any way (flag in gcc) to enable it. The regular -O
optimizations do not enable this. Is there anyway we could change the behavior of the preprocessor here?
I am using gcc 4.8.4 for my code.