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

后端 未结 9 1468
没有蜡笔的小新
没有蜡笔的小新 2020-12-22 18:30

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 <         


        
9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-22 19:09

    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.

提交回复
热议问题