The three logical operators are similar to the corresponding bitwise operators except that the operand is treated as a whole, where a value of 0 means 0 (or false), and any non zero value is taken as 1 (or true). The operators are:
symbol | meaning |
---|---|
! | logical NOT |
&& | logical AND |
|| | logical OR |
And where the result is guaranteed to be only 0 (false) or 1 (true). This result can be counted on and used arithmetically. Thus:
int z,y,x; ... z=(y&&x)*5;
will result in 'z' being either 0 or 5.
The logical AND, '&&', and logical OR, '||', operators have one special property. They are sequencing points. Which means that the order in which they are evaluated is guaranteed to be left to right within the precedence.
Further, when they are used in the conditional expression of an 'if' statement, as soon as the result is false, the other operands or clauses are guaranteed to not be evaluated. This is especially useful because it prevents an expression from being evaluated when some condition which says that it is meaningless or dangerously wrong (to the program) to evaluate it. Two common examples are array bounds checking or I/O limit or status checking.
int x,a[50]; /* must not evaluate: ++a[x] if x out of bounds */ if((x>=0)&&(x<50)&&++a[x]) statement;