liveBook · Manning

Comparison

As explained in Modern C

A comparison operator is a C operator that compares values and produces a Boolean result represented by zero or one.

In C, a comparison operator compares values and produces a Boolean result: false is represented by 0, and true by 1. The operators are ==, !=, <, >, <=, and >=. section 4.3 section 4.3.1

The comparison operators divide into these practical forms:

  • == tests equality, while != tests inequality. section 4.3.1
  • < and > perform strict less-than and greater-than comparisons. section 4.3.1
  • <= tests less than or equal, while >= tests greater than or equal. section 4.3.1
  • Comparison results can participate in arithmetic, control statements, and array indexing because they are 0 or 1. section 4.3.1

TAKEAWAY: Comparison operators return false or true, which are simply the values 0 and 1. This makes a comparison an expression that can be stored, counted, or used to select an array element. section 4.3.1 section 4.6

Counting comparison results

size_t c = (a < b) + (a == b) + (a > b); size_t d = (a <= b) + (a >= b) - 1; Each comparison contributes 0 or 1. Consequently, c is always 1, while d is 1 when a and b are equal and 0 otherwise. section 4.3.1

   size_t c = (a < b) + (a == b) + (a > b);
   size_t d = (a <= b) + (a >= b) - 1;


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":3},{\"line\":0,\"ch\":9}],[{\"line\":1,\"ch\":3},{\"line\":1,\"ch\":9}],[{\"line\":0,\"ch\":3},{\"line\":0,\"ch\":9}],[{\"line\":1,\"ch\":3},{\"line\":1,\"ch\":9}]]"}
!@%STYLE%@!

Inspect the compact expressions that combine comparison results arithmetically. section 4.3.1

How Modern C covers it

How deep it goes
Explains six comparison operators and their 0-or-1 results through worked expressions, without developing logical evaluation.
Examples
Uses equality-counting expressions and an array-indexing loop that classifies values relative to 1.0.
What it assumes
Assumes basic C expressions, operands, values, control statements, and size_t while teaching comparison semantics directly.
What you can do after
Apply comparison results as Boolean values in conditions, arithmetic expressions, and array subscripts.
How it connects
Connects comparisons to Boolean context, control statements, arithmetic, array indexing, and logical evaluation.

Also explained in

Compare how 8 books explain comparison →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.