2

I got code like this:

#include <iostream>

int f1() {
  std::cout << 1 << std::endl;
  return 1;
}

int f2() {
  std::cout << 2 << std::endl;
  return 2;
}

class Bar {
 public:
  Bar(int i, int j) {}
};

int main() {
  Bar bar(f1(), f2());
}

When the code compiled using gcc 7.4.0, the out put is 2 1, while when using clang 6.0, the out put is 1 2.

So I got questions: Is calling order of paramters an undefined behavior? If so, can I force compiler to call in order if f1() and f2() in order(in some cases the order of f1() and f2() matters)? And is this a good practice(compare with call them orderly and pass the result to the function)?

  • 2
    "_So I got questions: Is calling order of paramters an undefined behavior?_" No, not really. The order of evaluation, of function arguments, is **unspecified**. Edit: I don't really, agree with the current duplicate, since such code doesn't exhibit undefined behavior, and it doesn't talk about order, of evaluation, of function arguments. – Algirdas Preidžius Jun 19 '19 at 12:55
  • The order of evaluation of arguments is unspecified. As far as I know, there is no way to change that without rewriting your code. – gan_ Jun 19 '19 at 12:58
  • @AlgirdasPreidžius yeah, unspecified or implementation-defined is more correct. –  Jun 19 '19 at 12:58
  • The only way to sequence the calls is to declare temporary variables which store the results and *then* construct `bar`. So: `const auto r1 = f1(); const auto r2 = f2() Bar bar(r1, r2);` – Martin Bonner supports Monica Jun 19 '19 at 12:58
  • 4
    If the order matters, use variables. `auto i1 = f1(); auto i2 = f2(); Bar bar(i1, i2);`. It's very likely to produce exactly the same code except for the order. – molbdnilo Jun 19 '19 at 12:59
  • 3
    @reavenisadesk Unspecified, not implementation-defined (the implementation doesn't have to say how it does it, and it doesn't even have to be consistent). – Martin Bonner supports Monica Jun 19 '19 at 12:59
  • @MartinBonner aren't they the same thing? `implementation-defined behavior: unspecified behavior where each implementation documents how the choice is made` from C standard. –  Jun 19 '19 at 13:00
  • 2
    The better duplicate is: https://stackoverflow.com/questions/2934904/order-of-evaluation-in-c-function-parameters – mch Jun 19 '19 at 13:04
  • 1
    @mch I've added that to the target list – NathanOliver Jun 19 '19 at 13:07
  • 3
    @reavenisadesk No. "Implenentation defined" means the implementation has to document the order. In the case of order of evaluation, it doesn't. – Martin Bonner supports Monica Jun 19 '19 at 13:07

0 Answers0