C Language | Flow Control | Evaluating True and False

This article introduces relational operators for comparing values, equality operators for checking whether values match, and logical operators for combining conditions.

Relational and Equality Operations

Programs often need to branch or repeat work depending on a condition. In C, zero is false and any nonzero value is true. Comparison and logical operators produce an int result representing true or false.

Relational operators

Operator Result
A < B true if A is less than B
A <= B true if A is less than or equal to B
A > B true if A is greater than B
A >= B true if A is greater than or equal to B

Equality operators

Operator Result
A == B true if A and B are equal
A != B true if A and B are not equal

Logical operators

Operator Result
A && B true if both A and B are true
`A
!A true if A is false

Use A == B for equality. A = B assigns B to A. Assignment expressions can still be used intentionally, such as (A = B + C) == 0.

Logical operators have lower precedence than equality operators, and equality operators have lower precedence than relational operators.

Code 1

#include <stdio.h>

int main() {
 int iVar1 , iVar2;
 printf("Enter two values. >");
 scanf("%d %d" , &iVar1 , &iVar2);

 printf("iVar1 == iVar2 = %d\n" , iVar1 == iVar2);
 printf("iVar1 < 1000 = %d\n" , iVar1 < 1000);
 printf("iVar1 < iVar2 && iVar1 > 100 = %d\n" ,
   (iVar1 < iVar2) && (iVar1 > 100));
 return 0;
}

The && and || operators use short-circuit evaluation. For A && B, B is not evaluated if A is false. For A || B, B is not evaluated if A is true.

Code 2

#include <stdio.h>

int main() {
 int iVar = 0 , iTmp;
 iTmp = 0 && iVar++;
 printf("iVar = %d\n" , iVar);
 return 0;
}

iVar++ is not executed because the left operand already determines that the result is false. Be careful when expressions with side effects appear in logical operations.

To calculate exclusive OR (XOR), which is true only when exactly one operand is true, combine the logical operators:

(bool1 || bool2) && !(bool1 && bool2)

Code 3

#include <stdio.h>

int main() {
 int iBool1 , iBool2;
 printf("Enter two values. >");
 scanf("%d %d" , &iBool1 , &iBool2);
 printf("iBool1 XOR iBool2 = %d\n" ,
   (iBool1 || iBool2) && !(iBool1 && iBool2));
 return 0;
}