r/C_Programming • u/Low_Minimum9920 • Jun 15 '26
Question Question regarding unsigned integers
What's the difference between an unsigned int and a normal integer?
11
Upvotes
r/C_Programming • u/Low_Minimum9920 • Jun 15 '26
What's the difference between an unsigned int and a normal integer?
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:
and compiled it with GCC 13.3.0, using
gcc -o toy toy.c -Wall -Wextra -fsanitize=undefinedWhen 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.