Increment and decrement operator question | Sololearn: Learn to code for FREE!

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; }

9/30/2018 3:48:56 AM

Rohit Kashyap

7 Answers

New Answer

+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;

0

because b=(b-(--b))-(b-); Same with d;

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

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

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

0

Rohit Kashyap They are not the same. I was trying to say that a=a-((--a)-(a--)); has completely different computation flows.

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.