Tuesday, 5 February 2013

Logical Operators


Logical Operators

Operands of logical operations are considered true or false, that is non-zero or zero. Logical operators always return 1 or 0. Operands in a logical expression must be of scalar type.
Logical operators && and || associate from left to right. Logical negation operator ! associates from right to left.

Logical Operators Overview

OperatorOperationPrecedence
&&logical AND5
||logical OR4
!logical negation14

Logical Operations

&&0x
000
x01
||0x
001
x11
!0x
10

Precedence of logical, relational, and arithmetic operators was designated in such a way to allow complex expressions without parentheses to have an expected meaning:
c >= '0' && c <= '9';    /* reads as: (c >= '0') && (c <= '9') */
a + 1 == b || ! f(x);    /* reads as: ((a + 1) == b) || (! (f(x))) */
Logical AND && returns 1 only if both expressions evaluate to be nonzero, otherwise returns 0. If the first expression evaluates to false, the second expression will not be evaluated. For example:
a > b && c < d;     /* reads as  (a > b) && (c < d) */
/* if (a > b) is false (0), (c < d) will not be evaluated */
Logical OR || returns 1 if either of expression evaluates to be nonzero, otherwise returns 0. If the first expression evaluates to true, the second expression is not evaluated. For example:
a && b || c && d;  /* reads as: (a && b) || (c && d) */
/* if (a && b) is true (1), (c && d) will not be evaluated */

Logical Expressions and Side Effects

General rule regarding complex logical expressions is that the evaluation of consecutive logical operands stops at the very moment the final result is known. For example, if we have an expression a && b && c where a is false (0), then operands b and c will not be evaluated. This is very important if b and c are expressions, as their possible side effects will not take place!

Logical vs. Bitwise

Be aware of the principle difference between how bitwise and logical operators work. For example:
0222222 &  0555555     /* equals 000000 */
0222222 && 0555555     /* equals 1 */

~ 0x1234               /* equals 0xEDCB */
! 0x1234               /* equals 0 */

No comments:

Post a Comment