Can’t find the answer for
[++a + a++]
if a =2 then this result 7 but I can’t find why?
Evaluating statement containing both unary and arithmetic operator
The order in which your a++ and ++a statements are evaluated is undefined, so is the effect of your code.
Even if it seems to happens from right to left in your particular examples, you should not rely on that by any means.
This is what is called undefined beehive, and is dependent on what compiler you use.
In short if you want predictable behaviour when using operator ++ then the variable it is applied to should only appear once in the expression being evaluated.
Observe this code,
#include
using namespace std;
int main() {
int a=2;
int b=2;
cout<<++a+b++;
a=2;
cout<<endl<<++a+a++;
}
Here for first cout statement, evaluation is happening from left to right as the precedence of prefix is greater than postfix.
But, for second cout statement, the behavior is undefined.
Here the order of execution is right to left.
First a++ is evaluated, that incremented a to 3.
Now, a has become 3, thus after applying ++a, a will become 4.
so, ++a+a++=4+3=7
Hope, this would help.
Give a like if you are satisfied.
Please, mark it as resolved if it has been solved.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.