liveBook · Manning

Truthiness

As explained in Modern C, Third Edition

A truth value is the logical interpretation of a C value as true or false in a condition or logical operation.

C interprets a value as a condition: zero means false, while any value different from zero means true. This applies to scalar types, including numerical types and pointers. Use a truth value directly rather than redundantly comparing it with 0, false, or true. section 3.1

Use a value directly as a condition

The conditions if (i != 0) and if (i) have the same logical effect. The shorter form exposes C's truth-value rule; !i negates that interpretation. The bool type stores false and true, represented technically by 0 and 1. section 3.1

Logical operators consume truth interpretations. ! negates its operand, while && and || produce false or true. Applying !! to a value converts it explicitly to a normalized truth value, allowing it to serve as an index. section 4.4.2

// This never divides by 0.
if (b != 0 && ((a/b) > 1)) {
  ++x;
}

Short-circuit evaluation makes the second operand unnecessary when the first operand determines the result; here, b must be nonzero before division occurs. section 4.4.2

How Modern C, Third Edition covers it

How deep it goes
Defines zero and nonzero interpretation, covers scalar types and normalization, and demonstrates short-circuiting without descending into implementation internals.
Examples
Shows direct conditions, !! normalization in an array-counting loop, and && guarding division by zero.
What it assumes
Assumes basic C expressions and scalar types while establishing conditional interpretation and logical-operator behavior.
What you can do after
Apply truthiness by writing direct conditions, normalizing values with !!, and safely guarding operations with short-circuit logic.
How it connects
Connects conditional execution, scalar types, comparison operators, logical operators, and short-circuit evaluation.

Also explained in

Compare how 6 books explain truthiness →

Related concepts

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