A precondition is a condition that must hold before a function or operation is invoked. Make each function precondition explicit so invalid calls fail visibly rather than silently violating the algorithm. section 7.3
8 size_t gcd2(size_t a, size_t b) {
9 assert(a <= b);
10 if (!a) return b;
11 size_t rem = b % a;
12 return gcd2(rem, a);
13 }
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":1},{\"line\":0,\"ch\":2}],[{\"line\":0,\"ch\":5},{\"line\":0,\"ch\":11}],[{\"line\":3,\"ch\":7},{\"line\":3,\"ch\":13}],[{\"line\":0,\"ch\":5},{\"line\":0,\"ch\":11}],[{\"line\":3,\"ch\":7},{\"line\":3,\"ch\":13}],[{\"line\":0,\"ch\":5},{\"line\":0,\"ch\":11}],[{\"line\":3,\"ch\":7},{\"line\":3,\"ch\":13}],[{\"line\":1,\"ch\":1},{\"line\":1,\"ch\":2}],[{\"line\":1,\"ch\":7},{\"line\":1,\"ch\":13}],[{\"line\":2,\"ch\":0},{\"line\":2,\"ch\":2}],[{\"line\":2,\"ch\":7},{\"line\":2,\"ch\":9}],[{\"line\":2,\"ch\":15},{\"line\":2,\"ch\":21}],[{\"line\":4,\"ch\":7},{\"line\":4,\"ch\":13}],[{\"line\":3,\"ch\":0},{\"line\":3,\"ch\":2}],[{\"line\":0,\"ch\":5},{\"line\":0,\"ch\":11}],[{\"line\":3,\"ch\":7},{\"line\":3,\"ch\":13}],[{\"line\":4,\"ch\":0},{\"line\":4,\"ch\":2}],[{\"line\":2,\"ch\":15},{\"line\":2,\"ch\":21}],[{\"line\":4,\"ch\":7},{\"line\":4,\"ch\":13}],[{\"line\":5,\"ch\":0},{\"line\":5,\"ch\":2}]]"}
!@%STYLE%@!
The gcd2 implementation asserts a <= b before handling the termination case, computing a remainder, and making its recursive call. Modulo arithmetic preserves that precondition for subsequent calls. section 7.3
Use different mechanisms for different kinds of preconditions:
- Use assert to abort execution with an informative message when a function receives arguments that violate its precondition. section 7.3
- Use #if and #error to abort compilation when required platform facilities are unavailable. section 8.1.5
- Use static_assert for more sophisticated compile-time conditions, such as required relationships between type sizes. section 8.1.5







