badmad badmad - 3 months ago 9
C Question

Why does rand() + rand() produce negative numbers?

I observed that

rand()
library function when it is called just once within a loop, it almost always produces positive numbers.

for (i = 0; i < 100; i++) {
printf("%d\n", rand());
}


But when I add two
rand()
calls, the numbers generated now have more negative numbers.

for (i = 0; i < 100; i++) {
printf("%d = %d\n", rand(), (rand() + rand()));
}


Can someone explain why I am seeing negative numbers in the second case?

PS: I initialize the seed before the loop as
srand(time(NULL))
.

Answer

rand() is defined to return an integer between 0 and RAND_MAX.

rand() + rand()

could overflow. What you observe is likely a result of undefined behaviour caused by integer overflow.