参考变量c

参见英文答案 > What is the correct answer for cout << c++ << c;?4个
#include <iostream>
using namespace std;

int main()
{
    int x=80;
    int &y=x;
    cout<<"x"<<x<<" "<<"y"<<y++; 
    return 0;
}

上面的代码给了我以下输出

81 80

任何人都可以解释我x的价值如何变化到81? y的值是80,后来增加到81,但是如何在x中反映?

是否因为y是参考变量?那么这个值应该是在x和y两个修改过的吗?

解决方法

您有未定义的行为,因为您的操作在两个连续的 sequence points之间(功能参数评估之间没有序列点).您可以松散地将序列点视为“时间”标记,并且在两个连续的标记之间,您不能多次修改相同的变量.

基本上你的代码相当于

std::cout << x << x++; // undefined behavIoUr

因为y只是x的引用(别名).

1.9程序执行[介绍](强调我的)

14) Every value computation and side effect associated with a
full-expression is sequenced before every value computation and side
effect associated with the next full-expression to be evaluated.

15) Except where noted,evaluations of operands of individual
operators and of subexpressions of individual expressions are
unsequenced.
[ Note: In an expression that is evaluated more than once
during the execution of a program,unsequenced and indeterminately
sequenced evaluations of its subexpressions need not be performed
consistently in different evaluations. — end note ] The value
computations of the operands of an operator are sequenced before the
value computation of the result of the operator. If a side effect on a
scalar object is unsequenced relative to either another side effect on
the same scalar object or a value computation using the value of the
same scalar object,and they are not potentially concurrent (1.10),
the behavior is undefined.
[ Note: The next section imposes similar,
but more complex restrictions on potentially concurrent computations.
—endnote]

When calling a function (whether or not the function is inline),every
value computation and side effect associated with any argument
expression,or with the postfix expression designating the called
function,is sequenced before execution of every expression or
statement in the body of the called function. [ Note: Value
computations and side effects associated with different argument
expressions are unsequenced. — end note ] Every evaluation in the
calling function (including other function calls) that is not
otherwise specifically sequenced before or after the execution of the
body of the called function is indeterminately sequenced with respect
to the execution of the called function.9 Several contexts in C++
cause evaluation of a function call,even though no corresponding
function call Syntax appears in the translation unit. [ Example:
Evaluation of a new-expression invokes one or more allocation and
constructor functions; see 5.3.4. For another example,invocation of a
conversion function (12.3.2) can arise in contexts in which no
function call Syntax appears.

相关:https://stackoverflow.com/a/10782972/3093378

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...