r/C_Programming • • Jun 15 '26

Question Question regarding unsigned integers

What's the difference between an unsigned int and a normal integer?

11 Upvotes

93 comments sorted by

View all comments

Show parent comment

1

u/Ironraptor3 Jun 19 '26 edited Jun 19 '26

"It is more proper to say that signed integers use the most significant bit for a sign, an unsigned use it for the highest power of two the integer can represent"

I don't understand how (or if?) this contradicts what I claimed (that this results in having the same range). Also, in most implementations, I would expect signed to be using 2s-compliment, which would mean that the highest bit isn't just a "sign bit" but the negative of the highest power of two the integer can represent.

The whole claim you make about (un)signed over/under-flow seems to be... reversed? Pragmatically, I might agree that on any standard architectures I would expect signed overflow and underflow to wrap around. According to the standard though, unsigned integer over/under flow is well defined, from the standard:

"A computation involving unsigned operands can never produce an overflow, because arithmetic for the unsigned type is performed modulo 2N"

I made this toy program:

// toy.c
#include <limits.h>
#include <stdio.h>

int main(int argc, char** argv) {

  printf("Testing signed integers:\n");
  int int_max = INT_MAX;
  int int_min = INT_MIN;
  int int_one = 1;

  int int_overflow = int_max + int_one;
  printf("Overflow: %d\n", int_overflow);
  int int_underflow = int_min - int_one;
  printf("Underflow: %d\n", int_underflow);

  printf("Testing unsigned integers:\n");
  unsigned int uint_max = UINT_MAX;
  unsigned int uint_min = 0;
  unsigned int uint_one = 1;

  unsigned int uint_overflow = uint_max + uint_one;
  printf("Overflow: %u\n", uint_overflow);
  unsigned int uint_underflow = uint_min - uint_one;
  printf("Underflow: %u\n", uint_underflow);

  return 0;
}

and compiled it with GCC 13.3.0, using gcc -o toy toy.c -Wall -Wextra -fsanitize=undefined

When running ./toy, I get errors on lines 12 and 14 (the signed integer overflow and underflow, respectively), but I do not get any errors on unsigned integers...

Finally, I think that the "hard and fast rule", if any, is that code, where possible, should be self-documenting and match your intent. If it would be nonsense for a variable to take a value less than 0, use unsigned.