liveBook · Manning

Unsigned integer

As explained in Modern C, Third Edition

unsigned int is a C unsigned integer type that represents nonnegative whole numbers within an implementation-defined range.

A nonnegative C value

`unsigned x = 240u; unsigned y = x + 5u;` declares `x` and `y` with type `unsigned` (short for `unsigned int`). The `+` operator combines the values of its operands; evaluating `x` supplies the value 240. section 4.1 section 5.7.1

Unsigned integer types represent values from 0 through a type-specific maximum. For `unsigned`, that bound is `UINT_MAX` from `<limits.h>`; `unsigned long` and `unsigned long long` have their own bounds. Their precision is implementation-defined, so do not assume a particular maximum. The semantic type `size_t` is also unsigned and has a bound named `SIZE_MAX`. section 5.2 section 5.7.1

An unsigned type with precision `p` represents exactly 0 through `2^p − 1`. Its value is the sum of its set bits, each weighted by a power of two. For example, in a 16-bit unsigned type, 240 has bits 4, 5, 6, and 7 set. Unsigned arithmetic is closed over its range: mathematically, its results are described modulo `2^p`. section 5.7.1

TAKEAWAY

  • Check the relevant `_MAX` macro rather than assuming an unsigned type’s range. section 5.2 section 5.7.1
  • A narrow unsigned integer may be promoted before arithmetic; on the realistic platforms described here, that promotion produces `signed int`. section 5.2
typedef union unsignedInspect unsignedInspect;
union unsignedInspect {
  unsigned val;
  unsigned char bytes[sizeof(unsigned)];
};
unsignedInspect twofold = { .val = 0xAABBCCDD, };

This union overlays an `unsigned` value with an array of `unsigned char` so its individual bytes can be inspected. Byte order is implementation-defined; the order observed on one machine is not a portable rule. section 12.2

How Modern C, Third Edition covers it

How deep it goes
Derives the range from binary precision and describes modular arithmetic, then examines an unsigned object’s bytes.
Examples
Uses the set bits of 240 in a 16-bit type and a union that exposes an unsigned value’s bytes.
What you can do after
Evaluate/understand unsigned ranges and arithmetic, and distinguish a type’s numeric value from its implementation-defined byte order.
How it connects
Connects unsigned integers to `size_t`, integer promotion, binary representation, unions, and byte order.

Also explained in

Compare how 9 books explain unsigned integer →

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.