C语言宏中需要括号 [英] The need for parentheses in macros in C
问题描述
我尝试在以下代码中使用宏 SQR
的定义:
I tried to play with the definition of the macro SQR
in the following code:
#define SQR(x) (x*x)
int main()
{
int a, b=3;
a = SQR(b+5); // Ideally should be replaced with (3+5*5+3), though not sure.
printf("%d
",a);
return 0;
}
它打印 23
.如果我将宏定义更改为 SQR(x) ((x)*(x))
,则输出如预期的那样,64
.我知道在 C 中调用宏会将调用替换为宏的定义,但我仍然无法理解,它是如何计算 23
的.
It prints 23
. If I change the macro definition to SQR(x) ((x)*(x))
then the output is as expected, 64
. I know that a call to a macro in C replaces the call with the definition of the macro, but I still can’t understand, how it calculated 23
.
推荐答案
预处理器宏在代码编译之前执行文本替换,所以SQR(b+5)
转换为(b+5*b+5) = (6b+5) = 6*3+5 = 23
Pre-processor macros perform text-replacement before the code is compiled so
SQR(b+5)
translates to
(b+5*b+5) = (6b+5) = 6*3+5 = 23
常规函数调用会在将参数 (b+3) 传递给函数之前计算其值,但由于宏是预编译替换,因此运算的代数顺序变得非常重要.
Regular function calls would calculate the value of the parameter (b+3) before passing it to the function, but since a macro is pre-compiled replacement, the algebraic order of operations becomes very important.
这篇关于C语言宏中需要括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!