ok, i just need help understanding my compiler's methodology of analyzing this code. i know the "a++" increases the value of 'a' by 1. but i don't know why the following result is displayed. the answer comes out to be "7 6 7 5". what i was expecting was "7 7 7 7". in high school my professor told me that the compiler analyzes it from right to left, and then displays it from left to right. here's the code. i need step-to-step analysis. thanks in advance!
1 2 3 4 5 6 7 8 9 10
#include<iostream>
usingnamespace std;
#define endp cin.ignore()
int main()
{
int a=5;
cout<<a<<endl<<a++<<endl<<a<<endl<<a++;
endp;
return 0;
}
thanks for the quick reply. thing is, i am aware that i can use the variable one cout statement at a time. i'm only curious as to why my code outputs what it outputs. any thoughts?
i'm only curious as to why my code outputs what it outputs. any thoughts?
The rules of the C++ language do not explain the output.... the behavior is undefined. Looking for an answer is practically meaningless because the output can vary from compiler to compiler.
You might get "7 7 7 7"... or you might get "7 6 7 5" or you might get "1537 188993 48 0" or the program might crash. Literally anything can happen and still be within bounds of what the C++ language allows.
There is no deeper meaning. The only answer is "it's undefined"
Most operators do not specify the order in which operands are evaluated: The compiler is free to evaluate either the left -or right- hand operand first.
Now you see why using operators that cause side effects in the same statement are not so good, be it increment or decrement.