# || and |

sumaraghavi ragha

Ranch Hand

Posts: 118

Saurabh V Vakil

Greenhorn

Posts: 14

posted 8 years ago

if(++z > 5 || ++z > 6) z++;

uses short-circuit OR(||). short-circuit OR returns true if either operand is true. since z becomes 6 after entering if, the first condition evaluates to true. since the first operand returns true, it never bothers to check the second condition. so the if() is exited after checking ++z > 6 after which z is incremented(z++). hence the value is 7.

but the second case- if(++z > 5 | ++z > 6) z++;

uses non short-circuit OR, which, always evaluates both sides of the expression. when first operand is evaluated, z becomes 6. when second operand is evaluated, z becomes 7. finally, z is again incremented to become 8.

the important thing to remember is this: while using short-circuit or(||), if the first operand in the expression evaluates to true, the second operand will never be evaluated. but when you use non short-circuit or(|), second operand will be evaluated regardless of whether the first operand returns true or false. hope this helps.

Originally posted by sumaraghavi ragha:

int z = 5;

if(++z > 5 || ++z > 6) z++; // z = 7 after this code

versus:

int z = 5;

if(++z > 5 | ++z > 6) z++; // z = 8 after this code

if(++z > 5 || ++z > 6) z++;

uses short-circuit OR(||). short-circuit OR returns true if either operand is true. since z becomes 6 after entering if, the first condition evaluates to true. since the first operand returns true, it never bothers to check the second condition. so the if() is exited after checking ++z > 6 after which z is incremented(z++). hence the value is 7.

but the second case- if(++z > 5 | ++z > 6) z++;

uses non short-circuit OR, which, always evaluates both sides of the expression. when first operand is evaluated, z becomes 6. when second operand is evaluated, z becomes 7. finally, z is again incremented to become 8.

the important thing to remember is this: while using short-circuit or(||), if the first operand in the expression evaluates to true, the second operand will never be evaluated. but when you use non short-circuit or(|), second operand will be evaluated regardless of whether the first operand returns true or false. hope this helps.

posted 8 years ago

Have a look at short circuit operators. The way an expression is evaluated changes based on whether the operator is shorted or not

Originally posted by sumaraghavi ragha:

Hi All,

see the following code and expalin me the difference etween "||" and "|"

i am not a bigneer but getting confussion.

int z = 5;

if(++z > 5 || ++z > 6) z++; // z = 7 after this code

versus:

int z = 5;

if(++z > 5 | ++z > 6) z++; // z = 8 after this code

Have a look at short circuit operators. The way an expression is evaluated changes based on whether the operator is shorted or not