Increment and decrement operator question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Increment and decrement operator question

hello everyone can anyone explain why why output is diffrent even though they mean the same thing. i understand the shorthand assignment statement but standard statement is confusing me. #include<iostream> using namespace std; int main() { int a=5,b=5,c=5,d=5; a-=(--a)-(a--); cout<<"value of a : "<<a<<endl; //output 4 b=b-(--b)-(b--); cout<<"value of b : "<<b<<endl; //output -4 c+=(c++)+(++c); cout<<"value of b : "<<c<<endl; //output 19 d=d+(d++)+(++d); cout<<"value of c : "<<d<<endl; //output 18 return 0; }

30th Sep 2018, 3:48 AM
Rohit Kashyap
Rohit Kashyap - avatar
7 Answers
+ 1
Rohit Kashyap a+=d; is completely same as a=a+b; a+=b+c; is not the same as a=a+b+c; due to computation flow. The first case is a=a+(b+c) where we compute b at the firs, then c and then a. In the second case we have a=(a+b)+c; where a is computed at first, then b and then c;
1st Oct 2018, 5:29 AM
Sergey Ushakov
Sergey Ushakov - avatar
0
because b=(b-(--b))-(b-); Same with d;
30th Sep 2018, 4:54 AM
Sergey Ushakov
Sergey Ushakov - avatar
0
Rohit Kashyap please do not go into this type of scenario... this scenario is rarely (I have never seen this) used in practical examples... additionally, result depends on compiler version and same compiler may give different results at different time... that's the reason it is called undefined behaviour.... soz to conclude, don't go with pre and post increment operator in a single expression
30th Sep 2018, 7:33 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ketan Lalcheta sir im not using this in any of my programs. i just want to know how it will work. how the calculation done to get the answer
1st Oct 2018, 4:40 AM
Rohit Kashyap
Rohit Kashyap - avatar
0
Sergey Ushakov thank you for your answer. but i want to know why the answers are different even though both statements means the same thing
1st Oct 2018, 4:42 AM
Rohit Kashyap
Rohit Kashyap - avatar
0
Rohit Kashyap They are not the same. I was trying to say that a=a-((--a)-(a--)); has completely different computation flows.
1st Oct 2018, 5:04 AM
Sergey Ushakov
Sergey Ushakov - avatar
0
Sergey Ushakov i understood that. my question is about assignment operators a+=b; is the same as a=a+b; right. so essentially both statements means same thing. but as you can see both of them producing different outputs i want to know why is that im not able to understand in which order increment or decrement will occur.
1st Oct 2018, 5:12 AM
Rohit Kashyap
Rohit Kashyap - avatar