常数乘法的奇怪值

Strange value of the constant multiplication

本文关键字:常数乘      更新时间:2023-10-16
#include<iostream>
using namespace std;
#define P d2 + 2
int main()
{
    int d2 = 4;
    cout << P * 2;
    getchar();
    return 0;
}

为什么这段代码返回 8 而不是 12?当我引用 P 时,它有 6 个值。

在编译器之前运行的 C(和 C++)预处理器在使用指令 #include#define 时会执行严格的替换。换句话说,在预处理器运行后,编译器看到的只是

cout << d2 + 2 * 2; 

你应该尝试

#define P (d2 + 2)

甚至最好完全避免宏。

你忘记了大括号。宏在代码中直接替换。所以你的陈述是:

cout << d2 + 2 * 2

这是d2 + 4.

将宏编辑为

#define P (d2 + 2)