什么是cout的正确答案< c ++<< C;? [英] What is the correct answer for cout << c++ << c;?
问题描述
最近在采访中有一个以下的客观类型问题。
Recently in an interview there was a following objective type question.
int c = 0;
cout << c++ << c;
答案:
10
b。 01
c。未定义的行为
a. 10
b. 01
c. undefined behavior
我回答选择b,即输出将是01。
I answered choice b, i.e. output would be "01".
我被一个访问员告诉,正确的答案是选项c:undefined。
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< c ++<<将
ostream.operator c调用两次
ostream.operator
及更高版本 ostream.operator< <(c)
。
but as per my understanding for the statement cout << c++ << c
, the ostream.operator<<()
would be called twice, first with ostream.operator<<(c++)
and later ostream.operator<<(c)
.
我也检查了VS2010编译器的结果,其输出也是'01'。
I also checked the result on VS2010 compiler and its output is also '01'.
推荐答案
>
You can think of:
cout<<c++<<c;
As:
std::operator<<(std::operator<<(std::cout, c++), c);
C ++保证以前评估的所有副作用都将在序列点。在函数参数求值之间没有序列点,这意味着可以在参数 std :: operator<<<(std ::)之前计算参数
或之后。所以上面的结果是未定义的。 c
cout,c ++)
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 c
can be evaluated before argument std::operator<<(std::cout, c++)
or after. So the result of the above is undefined.
这篇关于什么是cout的正确答案< c ++<< C;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!