How to Create Multiple Comparisons with Logic in C Programming

By Dan Gookin

Some comparisons you will want to make when programming with C are more complex than those presented by the simple operators. For example, consider the following math-thingie:

-5 <= x <= 5

In English, this statement means that x represents a value between –5 and 5, inclusive. That’s not a C language if comparison, but it can be when you employ logical operators.

How to build a logical comparison in C

It’s possible to load two or more comparisons into a single if statement. The results of the comparisons are then compared by using a logical operator. When the result of the entire thing is true, the if condition is considered true.

LOGIC IS A TWEETING BIRD

#include <stdio.h>
int main()
{
  int coordinate;
  printf("Input target coordinate: ");
  scanf("%d",&coordinate);
  if( coordinate >= -5 && coordinate <= 5 )
  {
    puts("Close enough!");
  }
  else
  {
    puts("Target is out of range!");
  }
  return(0);
}

Two comparisons are made by the if statement condition in Line 9. That statement reads like this: “If the value of variable coordinate is greater than or equal to –5 and less than or equal to 5.”

Exercise 1: Create a new project using the source code from Logic Is a Tweeting Bird. Build the program. Run the code a few times to test how well it works.

How to add some logical operators in C

These C language logical comparison operators can be used in an if comparison when two or more conditions must be met.

Operator Name True When
&& and Both comparisons are true
|| or Either comparison is true
! not The item is false

Logic Is a Tweeting Bird uses the && operator as a logical AND comparison. Both of the conditions specified must be true for the if statement to consider everything in the parentheses to be true.

Exercise 2: Modify the source code from Logic Is a Tweeting Bird so that a logical OR operation is used to make the condition true when the value of variable coordinate is less than –5 or greater than 5.

Exercise 3: Create a new project that asks for the answer to a yes-or-no question with a press of the Y or N key, either upper- or lowercase. Ensure that the program responds properly when neither a Y nor N is pressed.

  • Logical operations are often referred to by using all caps: AND, OR. That separates them from the normal words and and or.

  • The logical AND is represented by two ampersands: &&. Say “and.”

  • The logical OR is represented by two pipe, or vertical-bar, characters: ||. Say “or.”

  • The logical NOT is represented by a single exclamation point: !. Say “not!”

  • The logical NOT isn’t used like AND or OR. It merely prefixes a value to reverse the results, transforming False into True and True into False.