|
|
Operators and Assignments - Bitwise vs Logical Operators
- the operand of every expression is evaluated before the operation is performed except for the short-circuit operators (&&, ¦¦) and ternary operator
- behaviour can produce unexpected results if you're not careful. For example, the following code illustrates what can occur if you try to set the value of a variable in an if condition and you always expect the new value to be available:
int i = 10;
int j = 12;
if( (i<j) ¦ (i=3) > 5 ) // value of i after oper: 3
if( (i<j) ¦¦ (i=3) > 5 ) // value of i after oper: 10
if( (i>j) & (i=3) > 5 ) // value of i after oper: 3
if( (i>j) && (i=3) > 5 ) // value of i after oper: 10
- with & and ¦ both operands are always evaluated
- with && and ¦¦ the second operand is only evaluated when it is necessary
- with ¦¦ (i<j) evaluates to true; there is no need to check the other operand as ¦¦ returns true if either of the operands are true
- with && (i>j) evaluates to false; there is no need to check the other operand as && returns true only if both operands are true. In this case one is false so there is no need to check the other operand
Also see
Bitwise operators
Logical operators
Example Code
Traps
- using a new value based on a short-circuit operation that was never evaluated
|