0

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.

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • 1
    Preprocessors don't do mathematical folding. They substitute content *verbatim* (and a few other neat things unrelated to your post). – WhozCraig Jun 29 '18 at 04:09
  • Possible duplicate of [Can the C preprocessor perform integer arithmetic?](https://stackoverflow.com/q/1560357/608639), [Can I add numbers with the C/C++ preprocessor?](https://stackoverflow.com/q/3539549/608639), [Macro perform integer arithmetic](https://stackoverflow.com/q/43513352/608639), [Can the C preprocessor perform arithmetic and if so, how?](https://stackoverflow.com/q/23306543/608639), [Mathematical operations during compiler preprocessing](https://stackoverflow.com/q/13317401/608639), etc. – jww Jun 29 '18 at 04:15

1 Answers1

2

No, the only time the preprocessor evaluates any expression is in #if / #elif.

You can fake arithmetic by implementing it in terms of token concatenation and a ton of macros, but that's much harder than simply doing

#define MY_NUM (2+2*2)

But there's no simple compiler switch because macro expansion is just token replacement.

melpomene
  • 84,125
  • 8
  • 85
  • 148