A C++ Program - Looks Simple yet not simple enough to Understand ! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

A C++ Program - Looks Simple yet not simple enough to Understand !

I'm having difficult time getting this program. How it prints true two when it shud print true one ? As a = 10, so if(a==a--) condition supposed to be true. how its treating the condition as false ? Someone please have a look at the code. it's just making me mad ! https://code.sololearn.com/c331j9216uhX/?ref=app

6th Apr 2017, 3:54 PM
alex merceR
alex merceR - avatar
6 Answers
+ 14
Based on your code: #include <iostream> using namespace std; int main() { int a=10; cout << a << a-- << endl; a=10; cout << a << --a << endl; return 0; } This should clear things up for you. :> You see, when a variable exists at different instances on the same line with post/pre-fix operators on them, different compiler does different dank stuff to interpret this shat. We have had a thread about this sometime ago. E.g. In C++, b = b++; does nothing while Java may interpret it as a net b++.
6th Apr 2017, 4:07 PM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Decrement operator has higher precedence. a == a-- First, a-- is executed. It sets "a" to 9 but returns 10. The "a" at the left has the value 9, which is not equal to 10 returned by a-- and that's why first if block doesn't run. a == --a First, --a is executed. It sets "a" to 9 and returns 9. The "a" at the left has the value 9, which is equal to 9 returned by --a and that's why second if block runs.
6th Apr 2017, 4:09 PM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 3
The decrement has the highest priority in your sample. ( a == a--) → ( a == (a--) ) 1) a = 10; 2) a == (a--) 3) a == 10 // postfix-- return old value (not a reference) of variable 4) a -= 1 5) 9 == 10 6) false ( a == --a) → ( a == (--a) ) 1) a = 10 2) a == (--a) 3) a -= 1 4) a == a // prefix-- return reference to variable 5) 9 == 9 6) true
6th Apr 2017, 4:18 PM
SUPER_S
SUPER_S - avatar
0
Thankyou for your valuable replies @JPM7. Those really helped a lot actually.
7th Apr 2017, 2:24 PM
alex merceR
alex merceR - avatar
0
i can understand that.
10th Apr 2017, 4:23 PM
alex merceR
alex merceR - avatar
- 1
So the differences between a-- and --a The primary value of a-- is 9, because it takes the value of a (which equals 10) and reduces it by one. The primary value of --a is still 10. It also takes the value of a and reduces it by one, but during the checking if condition it still 10.
6th Apr 2017, 4:11 PM
Ani Naslyan
Ani Naslyan - avatar