Predict output in Prefix and Postfix Increment Operators

Can someone please help me to get output of the following questions and also please explain how can I predict these outputs myself.

1
2
3
4
5
6
7
8
9
10
  int a=20,b;
  a+=a + ++a;
  cout<<a<<endl;
  a=20;
  b=a++ + ++a;
  cout<<b<<endl;
  b=a++ + ++a + ++a + a;
  cout<<b<<endl;
  b=a++ + a++ + ++a + a;
  cout<<b;
I tried it out. I now know it''s undefined. Well, what about->
Cout<<++a<<a<<a++; (a=20)
Cout<<++a<<++a<<a++;
Are statements like these also invalid? If not how to predict these?
> Are statements like these also invalid? If not how to predict these?

If 'a' is a scalar, the evaluations are unsequenced; behaviour is undefined.
If not, the evaluations are indeterminably-sequenced; there is no undefined behaviour, but the order can't be (portably) predicted.
See: http://en.cppreference.com/w/cpp/language/eval_order
I find that people often confuse precedence/associativity with order of evaluation. In f1() + f2() * f3(), the precedence rules say that you multiply before adding, but they do NOT say whether f1 is called before f2 is called before f3. That's order of evaluation.

In general, the compiler is free to do order of evaluation any way it likes. This applies to side effects too. It's easier to remember when the language DOES specify the order than when it DOESN'T. It does specify order of evaluation for ?:, &&, || and ,.

The link that JLBorges posted as the details.
Topic archived. No new replies allowed.