作业和序列点:这是怎么模糊的? [英] Assignment and sequence points: how is this ambiguous?

查看:138
本文介绍了作业和序列点:这是怎么模糊的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑C代码 a = a = a 。没有用于赋值的序列点,因此,当编译关于 a 上的未定义操作时,此代码会产生警告。

Consider the C code a = a = a. There's no sequence point for assignment, so this code produces a warning when compiling about an undefined operation on a.

a 可能具有的可能值是什么?看起来像 a 不可能更改值。这里是否存在未定义的行为或者编译器只是懒惰?

What are the possible values that a could have here? It seems like a couldn't possibly change values. Is there actually undefined behavior here or are compilers just being lazy?

推荐答案

序列点违规的未定义行为规则不会当值不能改变的情况下的异常。没有人在乎是否值的变化。重要的是,当您对变量进行任何类型的写入访问时,都会修改该变量。即使您为变量分配了一个已经存在的值,您仍然会对该变量执行修改。如果多个修改没有通过序列点分隔,则该行为是未定义的。

The rules of undefined behavior for sequence point violations do not make an exception for situations when "the value cannot change". Nobody cares whether the value changes or not. What matters is that when you are making any sort of write access to the variable, you are modifying that variable. Even if you are assigning the variable a value that it already holds, you are still performing a modification of that variable. And if multiple modifications are not separated by sequence points, the behavior is undefined.

可能会认为这种非修改修改不应该引起任何问题。但是语言规范不关心这些细节。在语言术语中,每次你在写一个变量时,你都在修改它。

One can probably argue that such "non-modifying modifications" should not cause any problems. But the language specification does not concern itself with such details. In language terminology, again, every time you are writing something into a variable, you are modifying it.

此外,在你的语言中使用单词问题似乎暗示您相信该行为是未指定的 。也就是说如变量的结果值是(或不是)模糊的。然而,在序列点违反中,语言规范不限于说明结果是未指定的 。它更进一步,并声明行为未定义。这意味着这些规则背后的理由不仅仅考虑了一些变量的不可预测的最终值。例如,在某些假想的硬件平台上,无序的修改可能导致编译器生成无效的代码,或类似的东西。

Moreover, the fact that you use the word "ambiguous" in your question seems to imply that you believe the behavior is unspecified. I.e. as in "the resultant value of the variable is (or isn't) ambiguous". However, in sequence point violations the language specification does not restrict itself to stating that the result is unspecified. It goes much further and declares the behavior undefined. This means that the rationale behind these rules takes into consideration more than just an unpredictable final value of some variable. For example, on some imaginary hardware platform non-sequenced modification might result in invalid code being generated by the compiler, or something like that.

这篇关于作业和序列点:这是怎么模糊的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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