C cout副作用测序

假设以下代码
#include <iostream>
using namespace std;

char one()
{
    cout << "one\n";
    return '1';
}

char two()
{
    cout << "two\n";
    return '2';
}

int main(int,char**)
{
    // 1:
    cout << one()
         << '\n'
         << two()
         << '\n';

    // 2:
    operator<<(
        operator<<(
            operator<<(
                operator<<(
                    cout,one()),'\n'),two()),'\n');
}

标记为1和2的行的执行与ideone编译一样,它打印如下:

two
one
1
2

从我的观点来看,我们在这里观察到的是未指定的行为,因为函数参数被解析的顺序是未指定的.

这是访问中的一个问题,打印上面给出的顺序(没有任何替代)应该是正确的答案,但它是否正确?

解决方法

你是对的,面试官对语言及其规则表现出一种令人惊讶的普遍缺乏的理解.

这两行是严格等效的,如果每个运算符<<要求第一行总是一个免费的功能(标准说是他们). 正如你所想的那样,函数调用间的顺序,除了其中一个参数是另一个参数的返回值,是不确定的顺序(前后,但未指定哪个):

1.9 Program execution [intro.execution]

[…]
15 […]
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. —end example ]
The sequencing constraints on the execution of the called function (as described above) are features of the function calls as evaluated,whatever the Syntax of the expression that calls the function might be.

命名所有部分:

cout << one() // a) execute one()           ("one\n")
              // b) output the return-value ("1")
     << '\n'  // c) output newline          ("\n")
     << two() // d) execute two()           ("two\n")
              // e) output the return-value ("2")
     << '\n'; // f) output newline          ("\n")

订购约束:

a < b < c < e < f
d < e < f

或不同的表示:

a < b < c <
          < e < f
d         <

因此,所有有效的全部订单:

abcdef "one\n1\ntwo\n2\n"
abdcef "one\n1two\n\n2\n"
adbcef "one\ntwo\n1\n2\n"
dabcef "two\none\n1\n2\n"

相关文章

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