[英]Unexpected output after running this little bit strange c code. Can anyone explain how this happened?
I am trying to understand how this code works,我试图了解这段代码是如何工作的,
int main () {
int m, k;
m = (k=5)+(k=8)+(k=9)+(k=7);
printf("m=%d\n",m);
printf("k=%d\n",k);
}
The out put: m=32 k=7输出:m=32 k=7
I have no idea how is the value of m become 32. I hope someone can help me to understand how this code works and how the outputs end up like this我不知道 m 的值是如何变成 32 的。我希望有人能帮助我理解这段代码是如何工作的,以及输出是如何结束的
Simplified explanation:简化解释:
When you use k=...
multiple times in the same expression, all assignments to that same variable are so-called "unsequenced side-effects".当您在同一个表达式中多次使用k=...
时,对同一个变量的所有赋值都是所谓的“未排序的副作用”。 Simply put, it means that C doesn't specify which operand of +
to evaluate/execute first nor does it specify the order in which the assignments will get carried out.简单地说,这意味着 C 没有指定+
的哪个操作数首先评估/执行,也没有指定执行分配的顺序。
So the compiler has no way of knowing which k
to evaluate/assign to first and therefore gets all confused.所以编译器无法知道首先评估/分配哪个k
,因此会感到困惑。 This is so-called "undefined behavior", anything can happen.这就是所谓的“未定义行为”,任何事情都有可能发生。
You have to solve this by splitting the expression up in several, each separated by a semicolon, which acts as a "sequence point", meaning all prior evaluations need to be done at the point where the ;
您必须通过将表达式分成几个来解决这个问题,每个都用分号分隔,分号充当“序列点”,这意味着所有先前的评估都需要在;
is encounterd.遇到。 Example:例子:
k=5;
k+=8;
k+=9;
m = k + 7;
Detailed explanation with standard references here: Why can't we mix increment operators like i++ with other operators?这里有标准参考的详细解释:为什么我们不能将像 i++ 这样的增量运算符与其他运算符混合使用?
This is undefined behavior.这是未定义的行为。 Your compiler warn about this您的编译器对此发出警告
warning: multiple unsequenced modifications to 'k' [-Wunsequenced]警告:对“k”的多个未排序的修改 [-Wunsequenced]
You can learn more about this here:您可以在此处了解更多信息:
The behaviour of the program is undefined .程序的行为是未定义的。
There are multiple unsequenced writes on k
in the expression表达式中的k
上有多个未排序的写入
(k = 5) + (k = 8) + (k = 9) + (k = 7)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.