[Solved] Why increment operator doesn’t work? [duplicate]


In answer to the C++ question for this code at http://codepad.org/cYXEuRuQ

#include<iostream.h>
int main()
{
int a=10;
a=a++;
cout<<a;
cout<<"\n";
a=++a;
cout<<a;
cout<<"\n";
a=(a++);
cout<<a;
cout<<"\n";
}

when compiled prints

cc1plus: warnings being treated as errors
In function 'int main()':
Line 5: warning: operation on 'a' may be undefined
Line 8: warning: operation on 'a' may be undefined
Line 11: warning: operation on 'a' may be undefined

This is a warning stating that the operation used is undefined and should not be used if possible. This is because in C++ the order of evaluation of ++ relative to other expressions is not defined and not the same across all compilers. (Generally it doesn’t matter and is not a problem except in edge cases like these)

The web site goes further and treats warnings as errors and does not run the code.


If you translate to Java it prints

10
11
11

as expected. What do you mean by “doesn’t work”?

The behaviour is defined in Java, but as LucTouraille points out its not defined in C++ so you can’t expect a particular behaviour which is the same for all compilers.

Another example.

int a = 3;
a = a++ * a++;
System.out.println(a); // will always be 12 in Java.

it is the same as

{
    int t1 = a;
    a = a + 1;
    int t2 = a;
    a = a + 1;
    a = t1 * t2;
}

4

solved Why increment operator doesn’t work? [duplicate]