What is run first inside a cout statement? (C++17)
Asked Answered
B

2

1

Say for example I have a long statement like

cout << findCurrent() << "," << findLowest() << "," << findHighest() << "," << findThird()<<"\n";

would findCurrent() be run before findLowest() like logic dictates?

Bibliographer answered 16/5, 2018 at 1:40 Comment(6)
#8704955 , #5215111 , #4176828Brodsky
@MitchWheat those links have little to do with this question (there is no UB here)Waterer
The order of evaluation is unspecified: #7719008Brodsky
@Goran Flegar I heard that there were changes in C++17. Didnt know what changed though. According to M.M it is left to right. That question was on an old version of c++.Bibliographer
@MitchWheat but you didn't flag it as duplicate - this was an automated comment from flagging it.Regicide
@Bibliographer the question didn't specify C++17, now that it does I'll remove the flag.Regicide
W
8

Since C++17 the functions are guaranteed to be called left-to-right, i.e. findCurrent() is called first, then findLowest() and so on.

C++17 Standard references: [expr.shift]/4 (referring to the expression E1 << E2):

The expression E1 is sequenced before the expression E2.

[over.match.oper]/2: (describing overloaded operators)

the operands are sequenced in the order prescribed for the built-in operator.

[intro.execution]/15:

An expression X is said to be sequenced before an expression Y if every value computation and every side effect associated with the expression X is sequenced before every value computation and every side effect associated with the expression Y.

Link to cppreference summary


Prior to C++17 the order of function calls was unspecified, meaning that they may be called in any order (and this order does not need to be the same on repeated invocations).

Waterer answered 16/5, 2018 at 1:58 Comment(3)
Funny how it took decades to get a simple sentence into the Standard that fixes all doubts.Giant
@DeiDei For a long time it was argued that leaving it unspecified allows the optimizer to generate faster code by using the fastest call order; however evidence didn't really back that up, and in a famous incident, they built the Windows NT kernel against the new evaluation order and it actually sped it upWaterer
@Waterer I found the source of that: the original proposal for the change in evaluation order. It says that some tests were faster but others were slower, so no difference on balance. (If changing it had made it faster, that would've been evidence that evaluation order actually does matter for optimisation.)Magnet
I
1

Before C++17, the order of evaluation is unspecified.

As of C++17, it's required to be evaluated left-to-right. See M.M's answer for standard quotation.

Iaverne answered 16/5, 2018 at 1:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.