Stuart A. answered 08/25/26
Programmer with over 30 years of experience with the C language.
The output of rand() is a positive integer. For this problem to occur it means that the RAND_MAX must be 0x7FFF if the integer is a 16 bit integer or 0x7FFFFFFF for a 32 bit integer.
Looking at the 32 bit case: 50% of the time the returned value will be in the range 0x7FFFFFFF - 0x40000000. If you add two return values from rand() the result will often be in the range 0xFFFFFFFF - 0x80000000. That is where the problem comes up, negative numbers have the high bit set to 1 and are represented as 1s complement. Numbers in that range are negative:
hex value integer value
0xFFFFFFFF -1
0xFFFFFFFE -2
...
0xFFA92743 -5691581
...
0x80000000 -2147483648
The same logic holds for the 16 bit case.
As an aside: in Microsoft Visual studio 2022 C the RAND_MAX is 0x7FFF so in that case it never comes up.