badmad badmad - 1 year ago 69
C Question

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

I observed that

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
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download