Introduction
You can combine results of multiple relations or logical operations by using logical operation. The logical operators are negation (!), logical AND (&&), and logical OR (||), in the same order of preference.
Explanation
-
Logical AND returns a true value if both relational expressions are true. Logical OR returns true if any of the expressions are true. Negations return complements of values of relational expressions, as shown in Table 3.2.
Table 3.2: Results of AND, OR, and Negation. R1
R2
R1 && R2
R1 || R2
! R1
T
T
T
T
F
T
F
F
T
F
F
T
F
T
T
F
F
F
F
T
-
Logical operators AND, and OR have higher priority than assignment operators, but less than relational operators. Negation operators have the same priority as unary operators, that is, the highest priority.
-
While evaluating logical expressions, C uses the technique of short circuiting. So if the expression is:
C1 && C2 && C3 && C4 if C1 is true
then only C2 is evaluated. If C1 is false, the expression returns false even if C2, C3, and C4 are true. So if C1 is false C2, C3, and C4 are not evaluated. Remember this when you are doing something such as searching in an array. For example, if you want to search for K in an array, the last value of which is subscript N, you can write the search condition in two ways:
I - (a [i] == K) && (i <= N) II - (i <= N) && (a[i] == K)
-
In case I you compare the array limit with K and check the bound. This is not correct because if the value of i is more than N you will get the array index out-of-bounds error.
-
In case II, you first check the bound and then compare the array element. This is correct because you will never compare the array element if value of i is more than N.
The technique of short-circuiting is applicable to the OR operator also. Thus if the expression is:
C1 || C2 || C3 || C4 if C1 is true
then the expression returns true and C2, C3 and C4 are not evaluated.
No comments:
Post a Comment