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,531
  • 1
  • 27
  • 69
ShenDaowu
  • 93
  • 3

3 Answers3

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
  • 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
  • 239,568
  • 38
  • 324
  • 436
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