+ 1
What’s wrong with increment cpp?
Why Increment postfix not worked In second If() statement? https://code.sololearn.com/cXHtde39A9cs/?ref=app
7 ответов
+ 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
+ 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
+ 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...
+ 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 ||.
+ 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.:)
+ 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. 👺
0
Инкримент остался неизменным. Это увеличение на единицу любого числа.