-2

Firstly, this is an attempt to understand how operator precedence works and not being used by me in any of my projects.

int *a=new int[3];
a[0]=3;a[1]=7;a[2]=11;
*a*=++*a**a++;
cout<<*(a-1)<<endl<<*a<<endl<<*(a+1);

Gives the following output,

4
112
11

I am expecting the following output,

64
7
11

Can someone please tell me how this is happening? Thank you

1 Answers1

3

Even by respecting operator precedences, you're not respecting sequence points and thus invoking undefined behavior.

Take a look at the cpp faq here: http://www.parashift.com/c++-faq/sequence-points.html

The C++ standard says (1.9p7),

At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place.

For example, if an expression contains the subexpression y++, then the variable y will be incremented by the next sequence point. Furthermore if the expression just after the sequence point contains the subexpression ++z, then z will not have yet been incremented at the moment the sequence point is reached.

The order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified

Additional info on sequence points: https://stackoverflow.com/a/4176333/1938163

Community
  • 1
  • 1
Marco A.
  • 43,032
  • 26
  • 132
  • 246