+ 5

Explain the code:

#include <iostream> using namespace std; int main() { int a=0; if(a&&++a) cout<<"0"; else cout<<a+1; return 0; } The output is 1 why it is not 2?

28th Apr 2017, 2:24 AM
Harshitha P N
3 ответов
+ 5
its because of the difference between && and & operators. if(a && ++a) Here a =0 which is false (0 is false 1 is true).since you used && operator , it saves memory by not proceeding to other half of the condition if first one is false(makes sense lol) So a=0 false , no need to go to second half as the net result is false either second is false or true. if(a & ++a) will check both conditions whether first is false or not. Hence output should be 2. Try it :-)
28th Apr 2017, 3:22 AM
Meharban Singh
Meharban Singh - avatar
+ 4
In general the use of pre/post-increments in conditionals and along with logical or ternary operators should be used with caution. Because increment and decrement operators have side effects, using expressions with increment or decrement operators in a preprocessor macro can have undesirable results.  In this case, since a is 0 (=false) before the &&, the rest of the conditional expression is not needed. Hence, you pass directly in the "else", without passing by ++a. So, in the "else", a is still equal to 0. (The code is well defined, overall.) Have a look here for more info: http://stackoverflow.com/questions/25725936/is-it-safe-to-put-increment-decrement-operators-inside-ternary-conditional-opera
28th Apr 2017, 2:42 AM
Billy Tsouvalas
- 1
It follows the same procedure as a for loop: validate and then assign... in this case ++a will add after the if-then-else and just before return 0;
28th Apr 2017, 3:09 AM
Ernesto De la Cruz
Ernesto De la Cruz - avatar