What’s wrong with increment cpp? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What’s wrong with increment cpp?

Why Increment postfix not worked In second If() statement? https://code.sololearn.com/cXHtde39A9cs/?ref=app

24th Jun 2019, 5:13 PM
Chicherin Alexey
Chicherin Alexey - avatar
7 Answers
+ 8
x is not > 5. Since the left hand side is false, the right hand side isn't evaluated and the second increment isn't carried out
24th Jun 2019, 5:20 PM
Anna
Anna - avatar
+ 4
Did you understand it? I think my explanation wasn't too great. Let me try again 😂 You have an expression a&&b. Both sides of the expression have to be true for the whole statement to be true. If a is false, the whole expression cannot be true, so b doesn't even need to be checked. In your case, b has a "side effect". It increments the value of the variable b. If you change the statement to if(x>5||b++), both sides of the expression will be evaluated. x>5 is still wrong, so now it will evaluate the right hand side and b will be incremented
24th Jun 2019, 6:02 PM
Anna
Anna - avatar
+ 4
Всё работает! :)) #include <iostream> using namespace std; int main() { int x=3,b=4; //first time if(x>0&&b++)cout<<b; else cout<<b; //second time if(b>4&&b++)cout<<b; else cout<<b; //increment postfix not worked cout<<b++; cout<<b; return 0; } it is incorrect condition if(x>5&&b++)cout<<b; x === 4 --> x>5 --> false --> b++ do not executing...
24th Jun 2019, 6:36 PM
Michail Getmanskiy
Michail Getmanskiy - avatar
+ 4
The C ++ compiler conditions && checks from left to right to the first "false" - in this case, the whole group of conditions && returns "false" and the right conditions are not even checked, and therefore their functions, operators, etc. are not called. In this case, b ++ will not be called. The C ++ compiler with the conditions || - checks them from left to right to the first "true" - in this case, the whole group of conditions || returns "true" and the right conditions are not even checked, and therefore their functions, operators, etc. are not called. And of course the execution order: && is higher than ||.
24th Jun 2019, 6:45 PM
Michail Getmanskiy
Michail Getmanskiy - avatar
+ 2
. How can it be. Why it works like this. It is too easy to make mistake if u never see it like me. %) If it is about optimization, thats nice, may be. Logic against optimization. No matter what - thank you for explanation.:)
24th Jun 2019, 5:57 PM
Chicherin Alexey
Chicherin Alexey - avatar
+ 1
I understand how it works after your first explanation👍🏻 because of AND logic. But i dont understend why this rule exist in language? For make it faster? ok, and overrides the rule of operations priority in same time. 👺
24th Jun 2019, 6:31 PM
Chicherin Alexey
Chicherin Alexey - avatar
0
Инкримент остался неизменным. Это увеличение на единицу любого числа.
9th Sep 2019, 6:39 PM
Роман Емельянов
Роман Емельянов - avatar