HeadlinesBriefing favicon HeadlinesBriefing.com

Unsigned Integers: A Case for Wider Adoption

Hacker News •
×

Dale Weiler argues that unsigned integers are underutilized in programming, despite their suitability for common tasks like array indexing and loop counts where negative values are irrelevant. The author contends that many developers default to signed integers, often due to perceived safety concerns that Weiler believes are misplaced and can lead to more dangerous coding practices.

A primary concern addressed is reverse loop iteration. While signed integers can be used, casting to signed types for loops like `for (int64_t i = size - 1; i >= 0; i--)` introduces potential for undefined behavior and exploitable vulnerabilities. Weiler proposes a robust idiom using unsigned integers: `for (size_t i = size - 1; i < size; i--)`. This approach leverages well-defined unsigned underflow to wrap around, correctly terminating the loop without problematic casts, and works even for zero-sized collections.

Further examples illustrate how unsigned arithmetic can simplify difference calculations and midpoint computations, which often pose risks with signed integers due to overflow and underflow. While calculating `mid = (low + high) / 2` can fail for both signed and unsigned types under certain conditions, Weiler suggests that using unsigned integers for array indices generally leads to more predictable and safer outcomes compared to the potential for invalid memory access with signed arithmetic.