考虑以下代码片段Case1:
int main()
{
int a;
a=printf("hello"),printf("joke");
printf("%d",a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
案例2:
int main()
{
int a;
a=(printf("hello"),printf("joke"));
printf("%d",a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
情形3:
int main()
{
int a;
a=10>8?(printf("hello"),printf("joke")):printf("hello");
printf("%d",a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
情形4:
int main()
{
int a;
a=10>8?printf("hello"),printf("joke"):printf("hello");
printf("%d",a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚当我在案例2中使用paranthesis时,然后我将输出作为hellojoke4,而不使用parantheis我得到输出为hellojoke5.
根据输出,当我尝试使用三元运算符时,然后使用paranthesis或不使用paranthesis执行相同的表达式,返回printf语句的最后输出值hellojoke4,那么如何在三元的情况下行为不同运营商.并且paranthesis的存在如何影响逗号的工作,它是作为分隔符还是作为操作符
这一切都归结为逗号运算符的低优先级.没有括号,表达式被分组为
(a=printf("hello")), printf("joke");
Run Code Online (Sandbox Code Playgroud)
所以,a从第一个printf开始,然后是第二个printf.在第二个示例中,printf分配了第二个结果a.
简化:
a = 1, 2; // (a = 1), 2; post-condition a==1
a = (1, 2); // a = (1, 2); is equivalent to a = 2; post-condition a==2
Run Code Online (Sandbox Code Playgroud)