cout<<的正确答案是什么? a ++<<一个;? [英] What is the correct answer for cout << a++ << a;?
问题描述
最近在一次采访中出现了以下客观类型问题。
Recently in an interview there was a following objective type question.
int a = 0;
cout << a++ << a;
答案:
a。 10
b。 01
c。未定义的行为
a. 10
b. 01
c. undefined behavior
我回答了选项b,即输出为 01。
I answered choice b, i.e. output would be "01".
但后来令我惊讶的是一名面试官告诉我,正确的答案是选项c:未定义。
But to my surprise later I was told by an interviewer that the correct answer is option c: undefined.
现在,我知道C ++中序列点的概念。对于以下语句,该行为是未定义的:
Now, I do know the concept of sequence points in C++. The behavior is undefined for the following statement:
int i = 0;
i += i++ + i++;
但根据我对语句 cout<<的理解, a ++<< a
中, ostream.operator<(<()
将被调用两次,首先是 ostream.operator<< (a ++)
和更高版本的 ostream.operator<<(a)
。
but as per my understanding for the statement cout << a++ << a
, the ostream.operator<<()
would be called twice, first with ostream.operator<<(a++)
and later ostream.operator<<(a)
.
我还在VS2010编译器上检查了结果,其输出也为'01'。
I also checked the result on VS2010 compiler and its output is also '01'.
推荐答案
您可以想到:
cout << a++ << a;
作为:
std::operator<<(std::operator<<(std::cout, a++), a);
C ++保证先前评估的所有副作用都将在序列点。函数参数评估之间没有顺序点,这意味着参数 a
可以在参数 std :: operator<<(std :: cout,a ++)
或之后。因此,上面的结果是不确定的。
C++ guarantees that all side effects of previous evaluations will have been performed at sequence points. There are no sequence points in between function arguments evaluation which means that argument a
can be evaluated before argument std::operator<<(std::cout, a++)
or after. So the result of the above is undefined.
C ++ 17更新
在C ++ 17中,规则已更新。特别是:
In C++17 the rules have been updated. In particular:
在移位运算符表达式中
E1 << E2
和E1>> E2
,E1
的每个值计算和副作用都要在E2
。
In a shift operator expression
E1<<E2
andE1>>E2
, every value computation and side-effect ofE1
is sequenced before every value computation and side effect ofE2
.
这意味着它需要代码来生成结果 b
,它输出 01
。
Which means that it requires the code to produce result b
, which outputs 01
.
这篇关于cout<<的正确答案是什么? a ++<<一个;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!