Back to course

Relational and Logical Operators

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 11: Relational and Logical Operators

These operators are crucial for decision-making (control flow).

Relational Operators

Relational operators compare two values and return a Boolean result (in C, 0 for False, non-zero, usually 1, for True).

OperatorDescriptionExample
==Equality (Is equal to)x == y
!=Inequality (Is not equal to)x != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y

Warning: A common mistake is using a single equals sign (=) (assignment) instead of double equals (==) (comparison). This mistake often leads to bugs where the assignment itself returns a non-zero (True) value.

Logical Operators

Logical operators combine two or more relational expressions.

OperatorDescriptionExample
&&Logical AND(age > 18) && (is_citizen) (True if both are true)
``
!Logical NOT!(is_raining) (Reverses the Boolean value)

Short-Circuit Evaluation

C uses short-circuit evaluation for && and ||:

  • In E1 && E2, if E1 is False (0), E2 is never evaluated.
  • In E1 || E2, if E1 is True (non-zero), E2 is never evaluated. This optimizes performance and prevents side-effects in the second expression if the first determines the outcome.