printf()中赋值运算符的问题 [英] issue with assignment operator inside printf()

查看:241
本文介绍了printf()中赋值运算符的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码

int main()
{
  int x=15;
  printf("%d %d %d %d",x=1,x<20,x*1,x>10);
  return 0;
}

输出为1 1 1 1

我期望将1 1 15 1作为输出,

x*1等于15,但是这里的x*11,为什么? 使用赋值运算符或在printf()中修改值会导致undefined behaviour?

x*1 equals to 15 but here x*1 is 1 , Why ? Using assignment operator or modifying value inside printf() results in undefined behaviour?

推荐答案

您的代码会产生未定义的行为.函数参数评估不相对于彼此排序.这意味着修改x=1中对x的访问权限不会与其他访问相关,例如x*1中的访问.该行为是未定义的.

Your code produces undefined behavior. Function argument evaluations are not sequenced relative to each other. Which means that modifying access to x in x=1 is not sequenced with relation to other accesses, like the one in x*1. The behavior is undefined.

再一次,它的不确定性不是因为您在printf()中使用了赋值运算符或修改值",而是因为您对与其他访问相关的未按排序的变量进行了修改访问到相同的变量.这段代码

Once again, it is undefined not because you "used assignment operator or modifying value inside printf()", but because you made a modifying access to variable that was not sequenced with relation to other accesses to the same variable. This code

(x = 1) + x * 1

出于相同的原因,

也具有未定义的行为,即使其中没​​有printf也是如此.同时,这段代码

also has undefined behavior for the very same reason, even though there's no printf in it. Meanwhile, this code

int x, y;
printf("%d %d", x = 1, y = 5);

非常好,即使它使用赋值运算符或在printf()内修改值".

is perfectly fine, even though it "uses assignment operator or modifying value inside printf()".

这篇关于printf()中赋值运算符的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆