Possible Duplicate:
Undefined Behavior and Sequence Points
int a=10;
a=a++;
a=++a;
a=(a++);
Can you guys please explain to me why none of these cases works?
Possible Duplicate:
Undefined Behavior and Sequence Points
int a=10;
a=a++;
a=++a;
a=(a++);
Can you guys please explain to me why none of these cases works?
Use it the right way:
int a = 10;
a++;
cout << a;
++a;
cout << a;
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;
}
The sequence for the algorithm:
int a=10;
a=a++;
System.out.println(a);
a=++a;
System.out.println(a);
a=(a++);
System.out.println(a);
Is as follows:
a=++a;
means that a
is incremented first before assigning the expression to a. Thus a = 11
.
a=(a++);
means can be understood like
b = a;
a++;
a = b;
Hence why you receiving value as 11
.
They all should work. I'm not sure what language your on. But if your on C/C++ it should work.