liveBook · Manning

Unsigned integer

As explained in Learn C++ by Example

An unsigned integer is an integer type representing only nonnegative values within a fixed range using unsigned arithmetic.

An unsigned integer represents nonnegative values, but it does not make negative input safe. In the triangle example, unsigned arithmetic provides a larger range, yet wraps to 0 after 4,294,967,295, making overflow harder to notice. Assigning -2 to an unsigned value compiles and produces a large positive number, removing the simple nonnegative check available with signed integers. section 2.3.4

Generating rows of a number triangle

A triangle generator works through 34 rows with signed int values, but the next row doubles 1,166,803,110 and exceeds the signed range. Signed overflow is undefined; unsigned arithmetic wraps instead. The practical lesson is to test the known safe limit rather than switching to unsigned merely to avoid negative values. section 2.3.4

Listing 2.14 Making sure there are no negative numbers by using a view
auto negative = [](int x) { return x < 0; };           #1
auto negatives = row | std::views::filter(negative);   #2
assert(negatives.empty());                             #3

Inspect a view-based check for negative values before choosing an integer representation; it demonstrates filtering and asserting that a row contains no negatives. section 2.3.4

How Learn C++ by Example covers it

How deep it goes
Explains range limits, overflow behavior, negative assignment, and the lost negative-value check, stopping short of implementation internals.
Examples
Uses a number triangle, row-count limits, signed overflow, unsigned wraparound, and assigning -2 to unsigned int.
What you can do after
Diagnoses overflow and representation mistakes without treating unsigned arithmetic as a general negative-value safeguard.
How it connects
Connects unsigned integers with signed integers, integer overflow, std::numeric_limits, assertions, and ranges views.

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 Learn C++ by Example. The section links point to the parts of the book it draws on.