4

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?

johnchen902
  • 9,431
  • 1
  • 26
  • 67
ShenDaowu
  • 93
  • 3

3 Answers3

24

Parentheses exist to override precedence. They have no effect on the order of evaluation.

R. Martinho Fernandes
  • 219,040
  • 71
  • 423
  • 503
  • 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
  • 1
    Talk 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
  • 223,042
  • 33
  • 293
  • 407
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
  • 72,003
  • 32
  • 177
  • 319
Thorsten Dittmar
  • 54,394
  • 8
  • 83
  • 132
  • 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