Logical Operators in C

Typically, C programmers use the int data type to represent logical data. If the data is zero, it is considered false. If it is nonzero, it is considered true.

C has three logical operators for combining logical values and creating new logical values. These three operators are the not operator, !, the and operator, &&, and the inclusive or operator, ||. The not operator, !, is a unary operator that changes a true value to a false value.

#include <stdio.h>

int main(void){
 
  int a = 7;
  int b = 0;
 
  printf("a = %d\n", a);
  printf("!a = %d\n", !a);
  printf("b = %d\n", b);
  printf("!b = %d\n", !b);
 
  return 0;
 
}

The and operator, &&, is a binary operator. Four distinct combinations of its operands are possible, and in only one case is the result true.

#include <stdio.h>

int main(void){
 
  int false = 0;
  int true = 1;
  int other = 2;
 
 
  printf("false && true = %d\n", false && true);
  printf("true && other = %d\n", true && other);
  printf("false && 0 = %d\n", false && 0);
  printf("!false && true = %d\n", !false && true);
 
  return 0;
 
}

The or operator is also a binary operator. Since it is a binary operator, four distinct combinations of values in its operands are possible. The result is false only if both operands are false; in all other cases it is true.

#include <stdio.h>

int main(void){
 
  int true = 1;
  int false = 0;
 
 
  printf("true || false = %d\n", true || false);
  printf("0 || 1 = %d\n", 0 || 1);
  printf("12 || true = %d\n", 12 || true);
  printf("!true || false = %d\n", !true || false);
  printf("false || 0 = %d\n", false || 0);
 
 
  return 0;
 
}

There are six relational operators that support logical relationships. They are all, of course, binary operators. Each of the six operators is a complement of another operator. The complement of the == operator is the != operator; the complement of the < operator is the >= operator; and, the complement of the > operator is the <= operator.

#include <stdio.h>

int main(void){
 
  int x = 7;
  int y = -3;
 
  printf("%d < %d is %d\n", x, y, x < y);
  printf("%d == %d is %d\n", x, y, x == y);
  printf("%d != %d is %d\n", x, y, x != y);
  printf("%d > %d is %d\n", x, y, x > y);
  printf("%d <= %d is %d\n", x, y, x <= y);
 
 
  return 0;
 
}

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s