C Tutorial/Operator/Logic Operators

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Boolean Operator in C

Character Set Boolean Operator && and || or

&& Operator

  1. && operator: evaluate a Boolean expression from left to right.
  2. Both sides of the operator must evaluate to true before the entire expression becomes true.

|| Operator

  1. || operator: evaluate from left to right.
  2. If either side of the condition is true, the whole expression results in true.

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.

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

  1. Logical operators AND, and OR have higher priority than assignment operators.
  2. Logical operators AND, and OR have lower priority than relational operators.
  3. Negation operators have the same priority as unary operators.

Logical operator

You can combine multiple relations or logical operations by logical operation.

The logical operators are negation (!), logical AND (&&), and logical OR (||),


#include<stdio.h>
main(){
  int c1 = 1,c2 = 2,c3 = 3;
  if((c1 < c2) && (c1<c3)){
     printf("\n c1 is less than c2 and c3");
  }
  if (!(c1< c2)){
     printf("\n c1 is greater than c2");
  }
  if ((c1 < c2)||(c1 < c3)){
     printf("\n c1 is less than c2 or c3 or both");
  }
}
c1 is less than c2 and c3
      c1 is less than c2 or c3 or both

Short circuiting

When evaluating logical expressions, C uses the technique of short circuiting.


C1 && C2 && C3 && C4

Ternary operator

Ternary operators return values based on the outcomes of relational expressions.

The general form of the ternary operator is:


(expr 1) ? expr2 : expr3

Testing letters with logic operator and (&&)

#include <stdio.h>
int main(void)
{
  char letter =0;                         
  printf("Enter an upper case letter:");  
  scanf(" %c", &letter);                  
  if ((letter >= "A") && (letter <= "Z")) 
  {
    letter += "a"-"A";                    
    printf("You entered an uppercase %c.\n", letter);
  }
  else
    printf("You did not enter an uppercase letter.\n");
  return 0;
}
Enter an upper case letter:R
     You entered an uppercase r.

The || is the logical OR operator.

#include <stdio.h>
 
int main()
{
    char c;
 
    printf("Y/y?");
    c=getchar();
    if(c=="Y" || c=="y")
    {
        printf("Bye!\n");
    }
    else
    {
        printf("Okay!\n");
    }
    return(0);
}
Y/y?1
      Okay!