Skip to study material
← Question index

QUESTION 58 · Operators

Explain relational, equality and logical operators with short-circuit evaluation.

5 marks

Answer in brief

Relational operators compare values. Logical operators combine conditions. These operators produce int results: 1 for true and 0 for false.

Relational operators

  1. Less than and greater than: Use < and >. For a = 5 and b = 8, a < b gives 1.
  2. Inclusive comparisons: Use <= and >= when equality is also allowed.
  3. Equality: Use == to test equality and != to test inequality. a == b gives 0 for 5 and 8.

Logical operators

  1. AND (&&): True only when both conditions are true. Example: age >= 18 && has_id.
  2. OR (: |)|True when at least one condition is true. Example: day == 6 || day == 7.
  3. NOT (!): Reverses the truth value. !0 gives 1 and !5 gives 0.

Short-circuit evaluation

For &&, C skips the right condition when the left condition is false. For ||, it skips the right condition when the left condition is true. For example, d != 0 && n % d == 0 checks d first. When d is zero, the remainder operation is skipped, avoiding division by zero in that expression.

Important points

Zero is treated as false; a non-zero value is treated as true. Write x > 0 && x < 10 to test a range. Do not write 0 < x < 10, because C first produces 0 or 1 from the first comparison and then compares that result with 10. Use == for comparison, not =.

Reference table

↔ Scroll horizontally on a small screen
Conditions with a = 5 and b = 8
ExpressionResultReason
a < b15 is less than 8.
a == b0The values differ.
a != b1The values differ.
a > 0 && b > 01Both conditions are true.
a == 0 || b == 00Neither value is zero.
!a0a is non-zero.

Key points

  • Logical operators normalise their result to 0 or 1.
  • Short-circuiting can prevent evaluating an unsafe expression.