Integer arithmetic operates on integer values through addition, subtraction, multiplication, division, and remainder operators. C supplements these operators with library interfaces for absolute values, quotient-and-remainder results, and checked arithmetic. section 8.2
Key safety rules:
- Division and remainder are defined except for division by zero and certain minimum signed-value cases. section 8.2
- Addition, subtraction, and multiplication require care because results can exceed the type’s bounds. section 8.2
- C23 checked functions such as ckd_add write the result through a pointer and return whether overflow occurred. section 8.2
Quotient and remainder together
auto res = div(x, y); printf("%d/%d is %d, remainder %d\n", x, y, res.quot, res.rem); The div family returns both results in a structure; C23 auto can infer its type. section 8.2
Table 8.5 Functions for integer arithmetic. Most of these are type-generic macros, but some also have function interfaces for specific types. \(x\) and \(y\) denote the arguments, \(\overline{x}\) is a bitwise complement, \(w\) the width, and \(m\) the maximum value of the type.
| Function | Description | Remark |
abs, labs, llabs |
\(|x|\) | Type independent |
div, ldiv, lldiv |
\(x\)/\(y\) and \(x\)%\(y\) |
Type independent |
ckd_add |
\(x\)+\(y\) (LS bits) & overflow flag |
Target dependent |
ckd_mul |
\(x\)*\(y\) (LS bits) & overflow flag |
Target dependent |
ckd_sub |
\(x\)-\(y\) (LS bits) & overflow flag |
Target dependent |
stdc_bit_ceil |
\(2^{\lceil \log_2 x\rceil}\) | \(1\) if \(x \equiv 0\), \(0\) if \(x > m/2\) |
stdc_bit_floor |
\(2^{\lfloor \log_2 x\rfloor}\) | \(0\) if \(x \equiv 0\) |
stdc_bit_width |
\(1 + {\lfloor \log_2 x\rfloor}\) | \(0\) if \(x \equiv 0\) |
stdc_count_ones |
Number of \(1\)-bits in \(x\) | Type independent |
stdc_count_zeros |
Number of \(1\)-bits in \(\overline{x}\) | Type dependent |
stdc_has_single_bit |
There is 𝑁 with \(x \equiv 2^n\) | Type independent |
stdc_first_leading_one |
\(w - {\big\lfloor \log_2 x\big\rfloor}\) | \(0\) if \(x \equiv 0\) |
stdc_first_leading_zero |
\(w - {\big\lfloor \log_2 \overline{x}\big\rfloor}\) | \(0\) if \(x\) has all bits set |
stdc_leading_ones |
\(w - {\big\lfloor \log_2 \overline{x}\big\rfloor} - 1\) | \(w\) if \(x \equiv 0\) |
stdc_leading_zeros |
\(w - {\big\lfloor \log_2 x\big\rfloor} - 1\) | \(w\) if \(x \equiv 0\) |
stdc_first_trailing_one |
One plus LS \(1\)-bit in \(x\) | \(0\) if \(x \equiv 0\) |
stdc_first_trailing_zero |
One plus LS \(0\)-bit in \(x\) | \(0\) if \(x \equiv 0\) |
stdc_trailing_ones |
One plus LS \(0\)-bit in \(x\) | \(w\) if \(x \equiv 0\) |
stdc_trailing_zeros |
One plus LS \(1\)-bit in \(x\) | \(w\) if \(x \equiv 0\) |
Compare absolute-value, quotient/remainder, checked-arithmetic, and bit-oriented integer functions with their constraints. section 8.2
