Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 与括号一起使用时宏更改的行为_C_Macros - Fatal编程技术网

C 与括号一起使用时宏更改的行为

C 与括号一起使用时宏更改的行为,c,macros,C,Macros,为什么此程序中的max(0,1)行为与max(1,0)不同 #define max(a,b) ((a)>(b))?(a):(b) int main() { printf("max(0,1) = %d \n",max(0,1)); printf("max(0,1)+1 = %d \n",max(0,1)+1); printf("max(0,1)+2 = %d \n",max(0,1)+2); printf("max(1,0) = %d \n",

为什么此程序中的
max(0,1)
行为与
max(1,0)
不同

#define max(a,b) ((a)>(b))?(a):(b)
int main()
{
    printf("max(0,1)    = %d \n",max(0,1));
    printf("max(0,1)+1  = %d \n",max(0,1)+1);
    printf("max(0,1)+2  = %d \n",max(0,1)+2);
    printf("max(1,0)    = %d \n",max(1,0));
    printf("max(1,0)+1  = %d \n",(max(1,0)+1));
    printf("max(1,0)+2  = %d \n",(max(1,0)+2));
    return 0;
}
输出:

max(0,1) = 1
max(0,1)+1 = 2
max(0,1)+2 = 3
max(0,1) = 1
max(1,0)+1= 1
max(1,0)+2= 1
如果使用了一个额外的括号,为什么它们表现良好

#define max(a,b) (((a)>(b))?(a):(b))

三元运算符
?:
的运算符优先级非常低:远低于加法。因此,你需要把三元数放在括号里,当它用来计算最大值时,最后的加法,如果有的话,是在三元数之后计算的

您始终可以取消拾取宏:


max(1,0)+1
取消勾选,将
max
的第一个定义改为
(1)>(0)?(1) :(0)+1
这当然是
1
。对于第二个定义,它是
((1)>(0)?(1):(0))+1
,这是
2

,因为
?:
条件运算符的运算符优先级低于二进制
+
运算符

因此
max(1,0)+1
被解释为
1>0?1:(0+1)


关于为什么不应该使用类似宏的函数的完美示例。

在宏展开后
#定义max(a,b)((a)>(b))?(a):(b)
,您的语句

printf("max(0,1)+1  = %d \n",max(0,1)+1);
printf("max(1,0)+1  = %d \n",(max(1,0)+1));  
看起来像

printf("max(0,1)+1  = %d \n",0 > 1 ? 0: (1+1));
printf("max(1,0)+1  = %d \n",(1 > 0 ? 1: (0+1)));

考虑一下扩展的结果:
max(0,1)+1
=>
((0)>(1))?(0):(1)+1
,这相当于
(0>1)?在第一种情况下,0:(1+1)
,与
((0)>(1))?(0:(1))+1
不同,后者基本上是
((0>1)?0:1)+1
。另请参见