C - #define 的意外输出
C - Unexpected output with #define
当我编译以下程序时,我得到的输出为 47。我预计输出为 144
#include<stdio.h>
#define FIRST_PART 7
#define LAST_PART 5
#define ALL_PARTS FIRST_PART + LAST_PART
int main() {
printf ("The Square of all parts is %d", ALL_PARTS * ALL_PARTS) ;
return(0);
}
预处理器在编译器之前工作。这是一个简单的 'stupid' 文本替换机制。因此:
ALL_PARTS
转换为 7 + 5
ALL_PARTS * ALL_PARTS
转换为 7 + 5 * 7 + 5
.
由于这种机制,建议宏的参数用括号括起来,也可以把整个宏用括号括起来,如:
#define ALL_PARTS (FIRST_PART + LAST_PART)
ALL_PARTS * ALL_PARTS
会变成
FIRST_PART + LAST_PART * FIRST_PART + LAST_PART
这是
7 + 5 * 7 + 5 = 7 + 35 + 5 = 47
所以 47 是 预期的答案。
如果您想查看您的预期结果,您需要将()
添加到您的define
#define ALL_PARTS (FIRST_PART + LAST_PART)
FIRST_PART + LAST_PART
将计算为 7 + 5(只不过是文本替换)。
你的表达式是 7 + 5 * 7 + 5 即 7 + 35 + 5(因为乘法比加法具有更高的优先级)。 7 + 35 + 5 的值当然是 47.
补救措施是使用 (FIRST_PART + LAST_PART)
作为您的定义。
您的预处理器评估为
printf ("The Square of all parts is %d", ALL_PARTS * ALL_PARTS) ;
然后
printf ("The Square of all parts is %d", FIRST_PART + LAST_PART * FIRST_PART + LAST_PART) ;
然后
printf ("The Square of all parts is %d", 7 + 5 * 7 + 5) ;
所以你的最终结果是47
要获得想要的结果,您可以使用
#define ALL_PARTS (FIRST_PART + LAST_PART)
只需要改变这个:
#define ALL_PARTS FIRST_PART + LAST_PART
为此:
#define ALL_PARTS (FIRST_PART + LAST_PAR)
FIRST_PART 是 7
LAST_PART 是 5
FIRST_PART + LAST_PART 是 7 + 5
7 + 5 * 7 + 5 = 7 + 35 + 5 = 47
要修复,请执行
#define ALL_PARTS ( FIRST_PART + LAST_PART )
你的代码展开为7+5*7+5 = 7+35+5 = 47。
这是一个很常见的故障。
当我编译以下程序时,我得到的输出为 47。我预计输出为 144
#include<stdio.h>
#define FIRST_PART 7
#define LAST_PART 5
#define ALL_PARTS FIRST_PART + LAST_PART
int main() {
printf ("The Square of all parts is %d", ALL_PARTS * ALL_PARTS) ;
return(0);
}
预处理器在编译器之前工作。这是一个简单的 'stupid' 文本替换机制。因此:
ALL_PARTS
转换为7 + 5
ALL_PARTS * ALL_PARTS
转换为7 + 5 * 7 + 5
.
由于这种机制,建议宏的参数用括号括起来,也可以把整个宏用括号括起来,如:
#define ALL_PARTS (FIRST_PART + LAST_PART)
ALL_PARTS * ALL_PARTS
会变成
FIRST_PART + LAST_PART * FIRST_PART + LAST_PART
这是
7 + 5 * 7 + 5 = 7 + 35 + 5 = 47
所以 47 是 预期的答案。
如果您想查看您的预期结果,您需要将()
添加到您的define
#define ALL_PARTS (FIRST_PART + LAST_PART)
FIRST_PART + LAST_PART
将计算为 7 + 5(只不过是文本替换)。
你的表达式是 7 + 5 * 7 + 5 即 7 + 35 + 5(因为乘法比加法具有更高的优先级)。 7 + 35 + 5 的值当然是 47.
补救措施是使用 (FIRST_PART + LAST_PART)
作为您的定义。
您的预处理器评估为
printf ("The Square of all parts is %d", ALL_PARTS * ALL_PARTS) ;
然后
printf ("The Square of all parts is %d", FIRST_PART + LAST_PART * FIRST_PART + LAST_PART) ;
然后
printf ("The Square of all parts is %d", 7 + 5 * 7 + 5) ;
所以你的最终结果是47
要获得想要的结果,您可以使用
#define ALL_PARTS (FIRST_PART + LAST_PART)
只需要改变这个:
#define ALL_PARTS FIRST_PART + LAST_PART
为此:
#define ALL_PARTS (FIRST_PART + LAST_PAR)
FIRST_PART 是 7 LAST_PART 是 5
FIRST_PART + LAST_PART 是 7 + 5
7 + 5 * 7 + 5 = 7 + 35 + 5 = 47
要修复,请执行
#define ALL_PARTS ( FIRST_PART + LAST_PART )
你的代码展开为7+5*7+5 = 7+35+5 = 47。 这是一个很常见的故障。