And does f(x)+(g(y))
can make sure call g(y)
first?
I know the order in expression is undefined in many case, but in this case does parentheses work?
Asked
Active
Viewed 409 times
4

johnchen902
- 9,531
- 1
- 27
- 69

ShenDaowu
- 93
- 3
-
possible duplicate of [Order of expression evaluation in C](http://stackoverflow.com/questions/9437683/order-of-expression-evaluation-in-c) – devnull Jul 05 '13 at 11:36
-
http://stackoverflow.com/a/9439459/2235132 – devnull Jul 05 '13 at 11:37
-
If not close, can somebody at least quote the relevant parts of the standard from the links above. – devnull Jul 05 '13 at 11:39
3 Answers
24
Parentheses exist to override precedence. They have no effect on the order of evaluation.

R. Martinho Fernandes
- 228,013
- 71
- 433
- 510
-
I would like to add a reference here http://en.cppreference.com/w/cpp/language/eval_order – DRC Jul 05 '13 at 11:28
-
1@musefan No. The order in which operations are done has nothing to do with the order in which the parameters for those operations are themselves evaluated. If you compare `(a() + b()) + c()` to `a() + (b() + c())`, the parenthesis change the order of the additions, but you can still *evaluate* `a()`, `b()`, and `c()` in any order you want. – David Schwartz Jul 05 '13 at 11:30
-
1Talk about [lazy reputation day](http://stackoverflow.com/a/17485851/596781)... :-) – Kerrek SB Jul 05 '13 at 11:33
-
@DavidSchwartz I wouldn't phrase it as "changes the order of the additions". It doesn't. I would phrase it as "changes *what* gets added to *what*". (a better example would use subtraction which is not associative) – R. Martinho Fernandes Jul 05 '13 at 11:39
12
Look ma, two lines!
auto r = g(y);
f(x) + r;
This introduces the all-important sequence point between the two function calls. There may be other ways to do it, but this way seems straightforward and obvious. Note that your parentheses do not introduce a sequence point, so aren't a solution.

John Zwinck
- 239,568
- 38
- 324
- 436
-
1
-
You were right, so I expanded a bit to explain and include a link (which funny enough, on Wikipedia shows this exact case as lacking a sequence point for C++). – John Zwinck Jul 05 '13 at 11:31
-
Shouldn't this be `auto &&r = g(y);`? Otherwise you might introduce an additional copy, depending what type `g` returns. – Steve Jessop Jul 05 '13 at 13:13
2
No. Unless the +
operator is redefined, things like that are evaluated left to right. Even if you were able to influence the precedence in the operator, it wouldn't necessarily mean that f
and g
were evaluated in the same order. If you need f
to be evaluated before g
, you can always do:
auto resultOfF = f(x);
auto resultOfG = g(x);
resultOfF + resultOfG;

rubenvb
- 74,642
- 33
- 187
- 332

Thorsten Dittmar
- 55,956
- 8
- 91
- 139
-
You're welcome. It's a C++11 feature, but a handy one at that, especially in exactly this case :) – rubenvb Jul 05 '13 at 11:37