c++ - What is the difference between && and ||? -


i'm getting difficult understand how following programs work, kindly me in understanding.

int x=2,y=0; 

(i)

if(x++ && y++) cout<<x<<y; 

output:

(ii)

if(y++ || x++) cout<<x<<" "<<y; 

output: 3 1

(iii)

if(x++||y++) cout<<x<<" "<<y; 

output: 3 0

kindly explain me how program working , also, makes difference between (ii) , (iii).

you looking @ "c++ puzzle" using 2 languages tricks.

the first postincrement uses value of variable first, increments variable.

so x++ has value 2 in expression , x becomes 3 y++ has value 0 in expression, , y becomes 1

&& , || or

both operators short-circuiting.

look @ && first.

in order , true, both sides must true (non-zero)

since x++ && y++, first x++ happens, , since non-zero (true) y++ has happen determine whether result true or not. therefore x 3 , y 1.

the second case same. y zero, in order determine if or true, if statement executes second half of expression.

the third case, since in opposite order, never executes y++ because

x++ || y++

the first half being x++, true, compiler not bother execute second half of test.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -