Question:
I would like to understand what rules determine the order of evaluation of the values of expressions in the general case.
Let's say there is a code like this
int readValue()
{
int v;
cin >> v;
return v;
}
int main()
{
cout << readValue() << ' ' << readValue() << '\n';
return 0;
}
As you know , the bitwise shift operator is calculated from left to right – but when you enter 1 2
, the output is 2 1
(Microsoft's compiler), what is the reason for this?
Does this code generate undefined behaviour
or is it just the output order is undefined ?
If you remove the reading code – everything is pretty predictable
int readValue(int v)
{
return v;
}
int main()
{
cout << readValue(1) << ' ' << readValue(2) << '\n';
return 0;
}
output – 1 2
what's the matter ?
Answer:
The statement that these bitwise shift operators are evaluated from left to right is true, but it only tells you the order in which successive <<
operators are applied to their immediate operands. In this case, the direct operands of the <<
operators are some temporary intermediate values of the int
type
cout << __tmp_int1 << ' ' << __tmp_int2 << '\n';
Here about this (and only about this) expression in this case, we can say that it is calculated from left to right. That is, the value of __tmp_int1
will be printed earlier, and the value of __tmp_int2
– later.
And as for the order and moment of preparation of these intermediate values - it is not limited to the above statement. That is, the compiler can do and
int __tmp_int1 = ReadValue();
int __tmp_int2 = ReadValue();
and vice versa
int __tmp_int2 = ReadValue();
int __tmp_int1 = ReadValue();
or generally intertwine the preparation __tmp_int1
and __tmp_int2
with <<
calls in some unpredictable way. The main thing is that the value is ready for the moment when it is needed. Nothing more is specified.