0
#include <iostream> using namespace std; int main() { int k=5; int m; m=(m=5)+(++k+k++ + ++k+k++); cout<<m<<" "<<k; return 0; }
The compiler gives the out put at 34 and 9 but when i do it manually, I get 33 and 9.
9 Answers
+ 2
@Aneesh
C++ doesn't follow certain definite rules while evaluating multiple prefix and postfix in a single expression. If you would try 10 different compilers you would get 3-4 different results.
So multiple prefix and postfix evaluation depends on compiler.
But the output for
cout<<++a<<a++<<a;
would be constant in most compilers.
+ 1
@Megatron Yeah, true but this was an exam question and i gave the output as 33 and 9 and i got marked wrong for that. So thats why i wanted to know.
@Pranav What're you doing here huh xD?
0
I'm getting 26 and 7 on my machine. You sure that's the correct code?
0
Oh, sorry the 33 and 9 is when k=5!
0
This is actually really strange, but I've done some testing. Check out this code, it might shed some light on this.
int main(){
int x = 3;
cout << x++ << " " << x++ << endl;
return 0;
}
I get the numbers 4 and 3, in that order. I'm thinking it's because when the numbers are incremented, it happens from right to left. So when you write (m=5)+(++k + k++ + ++k + k++), you're adding the numbers 5, 7, 8, 7, and 7, respectively, which add up to 34.
0
After incrementing from right to left we get m=(5)+(9+7+7+5)
Which is 33
0
Remember that the prefix increment happens before the rest, so k is incremented to 7 before anything else inside the statement is done. Then it evaluates the postfix increments from right to left, after everything else. So it's closer to (5)+(7+8+7+7), or 34.
0
I didnt get you, could you explain in steps please
0
But post increment operators have higher precedence right? @Sean