0

I have following snippet:

#include <iostream>

void test(int arg_1, int arg_2, int arg_3, int arg_4)
{
    std::cout << arg_1 << ", " << arg_2 << ", " << arg_3 << ", " << arg_4 << std::endl;
}

I ran following scenarios but i am unable to understand them. Please explain them.

Case-1:

int i;
i = 200;
test(i, i, i, i);

Case-1 - Output:

200, 200, 200, 200

Case-2:

int i;
i = 200;
test(i++, i++, i++, i++);

Case-2 - Output:

203, 202, 201, 200

Case-3:

int i;
i = 200;
test(i++, i+=10, i++, i++);

Case-3 - Output:

212, 213, 201, 200

Case-4:

int i;
i = 200;
test(i++, i++, i+=10, i++);

Case-4 - Output:

212, 211, 213, 200

Case-5:

int i;
i = 200;
test(i++, i++, i++, i+=10);

Case-5 - Output:

212, 211, 210, 213

Case-6:

int i;
i = 200;
test(i++, i+=10, i++, i+=1);

Case-6 - Output:

212, 213, 201, 213

Case-1 is just for reference; while Case-2 is easy to understand. But from Case-3 to Case-6; i have no idea what is going on. Kindly explain such behavior.

Also; are there any official docs/reference for such behavior?

ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83
namit
  • 6,042
  • 3
  • 30
  • 39
  • 1
    Except case 1, all your cases leads to *undefined behavior*. – Some programmer dude Jul 23 '19 at 06:46
  • 1
    I'm not a language lawyer, but I suspect almost all of your sample cases (save for #1) are in undefined behavior territory. – selbie Jul 23 '19 at 06:46
  • 2
    The official doc is the C++ standard, which says "The order of argument evaluation is undefined". This changes however in C++17. I don't have standard nearby, but hopefully somebody else can provide a proper answer – Yksisarvinen Jul 23 '19 at 06:46
  • 1
    As answered in https://stackoverflow.com/questions/598148/is-it-legal-to-use-the-increment-operator-in-a-c-function-call this is `undefined behaviour`. – Zaiborg Jul 23 '19 at 06:50
  • @Yksisarvinen: Ok. I hope someone will explain the correct behavior has per C++17(if it is there). To me; case3 to 5 are following some order; but for case-6, i am clueless. – namit Jul 23 '19 at 06:52
  • https://stackoverflow.com/questions/38501587/what-are-the-evaluation-order-guarantees-introduced-by-c17 – namit Jul 23 '19 at 07:16

1 Answers1

0

the short answer for you is:

The order of evaluation of any part of any expression, including order of evaluation of function arguments is unspecified

refer to this:

https://en.cppreference.com/w/cpp/language/eval_order

ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83