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/flatfinger Jun 16 '26

Comparisons are among the operations that behave differently.

The authors of the Standard expected that on any commonplace hardware the math for addition, subtraction, left-shift, multiplication, and bitwise operators would be the same in cases where the result is stored directly to an int or unsigned int object, or is an operand to one of the above operators whose result is used likewise, but failed to actually specify that. As a consequence, on platforms where int is 32 bits, gcc will sometimes process uint32a = uint16a*uint16b; (which the Standard treats as equivalent to uint32a = (int)uint16a*(int)uint16b;) wildly differently from uint32a = (unsigned)uint16a*(unsigned)uint16b;. The latter would have defined arithmetically-correct behavior in all cases, while the former may cause arbitrary memory corruption in cases where uint16a exceeds INT_MAX/uint16b.