blogger Indonesia

Follow judhyns blog

LOGICAL OPERATOR

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.

Program

#include  main( ) {   int c1,c2,c3;  printf("ENTER VALUES OF c1, c2 AND c3"); scanf("%d%d%d",&c1.&c2,&c3);  if((c1 < c2)&&(c1 
Input
c1= 2; c2= 3; c3= 4; 
Output
ENTER VALUES OF c1, c2 AND c3 2 3 4 c1 is less than c2 and c3 c1 is less than c2 or c3 or both 

Explanation

  1. 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

  2. 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.

  3. 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) 
  4. 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.

  5. 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:

feed

PR Check

activesearchresults

judhyn's blog

 

http://www.judhyn.blogspot.com | |