C - Building a logical comparison inside if statement

Introduction

It's possible to load two or more comparisons into a single if statement.

The results of the comparisons are compared by using a logical operator.

When the result of the entire thing is true, the if condition is considered true.

Demo

#include <stdio.h> 

int main() // ww w  . j  a  va  2s  . c  om
{ 
      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); 
}

Result

Two comparisons are made by the if statement condition.

Logical operators

The C language logical comparison operators are shown in the following table.

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

OperatorNameTrue When
&& and Both comparisons are true
|| or Either comparison is true
! notThe item is false

Related Topic