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.

4

2 回答 2

2

不,预处理器评估任何表达式的唯一时间是#if/ #elif

您可以通过令牌连接和大量宏来实现它来伪造算术,但这比简单地做起来要困难得多

#define MY_NUM (2+2*2)

但是没有简单的编译器切换,因为宏扩展只是令牌替换。

于 2018-06-29T04:02:30.320 回答
0

预处理器有自己的常量值计算器,它使用这个计算器来获取所有条件运算符#if #elif 中表达式的值。

即使可以从预处理器标记的替换列表中折叠常量,它也永远不会这样做,仅仅是因为它不知道它是预处理 C 代码还是其他一些文本/语言。

C 预处理器具有通用性,它不仅仅针对 C 语言预处理。

C 编译器可能在解析 C 标记的解析器中拥有自己的常量折叠。

于 2018-06-29T07:54:41.200 回答