Skip to content

← Values, Types, Initialisation step 1 of 4

Easy Primitives

Choose integer width and overflow behavior

An int has at least 16 bits of width; C++ does not require it to be 32 bits. The standard integer types have minimum ranges and an ordering of storage sizes:

sizeof(char) == 1 <= sizeof(short) <= sizeof(int)
                 <= sizeof(long) <= sizeof(long long)

sizeof measures C++ bytes, which are not necessarily 8 bits. Built-in types are useful when their guaranteed range is sufficient. When a format or calculation requires an exact width, make that requirement explicit.

Exact-width integer types

The <cstdint> header provides types such as std::int32_t, std::uint32_t, std::int64_t and std::uint64_t on implementations that support those exact widths. They are available in this exercise's environment.

Width and overflow behavior are separate choices. A signed 64-bit type does not make overflowing addition safe. Unsigned 64-bit arithmetic wraps modulo 2^64; signed arithmetic outside its representable range has undefined behavior.

Choose a type whose range covers the values you need, and check arithmetic that might exceed that range. For modular calculations, choose an unsigned type deliberately. An exact-width field also does not define byte order or struct padding; file and network formats still need explicit serialization.

Your task

std::int64_t checksum(const std::vector<std::int64_t>& values);

Compute a simple additive checksum:

  1. Start an unsigned 64-bit accumulator at zero.
  2. Convert each signed input to std::uint64_t and add it to the accumulator.
  3. Convert the final accumulator to std::int64_t and return it.

Every input fits std::int64_t. Converting a negative input to unsigned uses modulo 2^64, and unsigned addition uses the same modulus. In C++20, the final integer conversion is also defined modulo 2^64: unsigned results above INT64_MAX become negative signed values. This is a value conversion, not reinterpret_cast.

Input Result
[1, 2, 3] 6
[] 0
[100, -250] -150
[3000000000, 3000000000] 6000000000
[9223372036854775807, 1] -9223372036854775808

The last row specifies modular arithmetic, not a mathematical sum that fits the signed return type. This simple sum is not a cryptographic checksum and does not distinguish different input orders.

The starter accumulates into int. On this platform, total += v performs its addition in the wider signed type of v, then converts the result back to int. That conversion can lose the upper bits even when the addition itself fits. Other inputs can also overflow the signed intermediate addition. Use an unsigned 64-bit accumulator throughout instead of widening an already damaged result.