1

I was trying to get used to Pointer arithmetics, with increment operators both on the address and value pointed to by the pointer.

I used std::cout for checking my understanding, I found what I couldn't easily digest, let's have a look( This is a code inside of the function main ):

int R = 0;
std::cout << 0 << 1 << 2 << 3 << endl;

std::cout << R++ << R++ << R++ << R++ << endl;

R = 0; // R value reset to Zero;
std::cout << ++R << ++R << ++R << ++R << endl;

The result will be:

0123
3210
4444

I tried to figure out behavior of cout with postfix ++, but when I took its behavior with the prefix ++ into the same consideration, I totally collapsed. And simply realized: it's a stackoverflow issue. Thank you guys in advance.

Physician
  • 483
  • 2
  • 7
  • Thank you guys, I appreciate your response. On my side, it's clear now that's about a topic beyond my knowledge at this moment. Thanks:) – Physician Jul 26 '16 at 06:31

2 Answers2

1
std::cout << R++ << R++ << R++ << R++ << endl;

is translated as:

std::cout.operator<<(R++).operator(R++).operator(R++).operator(R++).operator<<(endl);

Since the language does not guarantee the order of evaluation of function arguments, your code has undefined behavior.

If you want to force an order, use parenthesis to force the compiler to evaluate the expressions in the order that you expect;

((((std::cout << R++) << R++) << R++) << R++) << endl;
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

It's one of C++s undefined behaviors: modifying the same variable at the same sequence point.

You should use separate cout statements (separated by ;) to get guaranteed results:

int R = 0;
std::cout << 0;
std::cout << 1;
std::cout << 2;
std::cout << 3 << std::endl;

std::cout << R++;
std::cout << R++;
std::cout << R++;
std::cout << R++ << std::endl;

R = 0; // R value reset to Zero;
std::cout << ++R;
std::cout << ++R;
std::cout << ++R;
std::cout << ++R << std::endl;
Dutow
  • 5,638
  • 1
  • 30
  • 40