In C++, the % operator only has defined results if both sides of the % operator are positive.
rand() % MININT
rand() will always give you a positive number, but in your example, MININT is negative, therefore this has undefined behavior and is very bad.
FWIW, you shouldn't be using rand() anyway. You should be using C++11 <random> header:
1 2 3 4 5 6 7 8 9 10 11
#include <random>
#include <ctime>
// The random number generator. Made global for simplicity
std::mt19937 rng( time(nullptr) ); // <- use the current time to seed it
// function to generate a random number between [-10, 10]
int randomin() // <- (don't put void in the parenthesis -- that's a goofy C thing and isn't necessary in C++)
{
return std::uniform_int_distribution<int>(-10, 10)(rng);
}
> In C++, the % operator only has defined results if both sides of the % operator are positive.
The result of a%b is undefined if and only if the second operand is zero. Otherwise,
if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a
.
Truncation towards zero during division and (a/b)*b + a%b == a together mean that the result of a%b has the same sign as the dividend - that is positive for positive a and negative for negative a.
In legacy C++, if one or both operands were negative, the sign of the result of a%b was implementation-defined.
JLBorges: Thanks for the clarification. I was thinking in legacy C++ (didn't realize they changed it), and I get implementation-defined and undefined mixed up because they're both to be avoided.
We can't really avoid implementation-defined behaviour; for instance, sizeof(int) and the mapping of source file characters to the execution character set are implementation-defined.
Undefined behaviour and unspecified behavior should be avoided, though.