// returns a random integar between minVal and maxVal
int random(int minVal, int maxVal)
{
// int rand(void); included by default from newlib
return rand() % (maxVal-minVal+1) + minVal;
}
This can be an issue in code like this (from asterocks):
int rockyadd[12];
...
asterockyspeed[i]=rockyadd[random(12)]
Because of the +1, random can return 12, which is out-of-bounds for that array.
It’s common for random number functions to use an inclusive lower bound and an exclusive upper bound because of the way the limited is implemented.
(Usually people just use the modulo (%) operator, despite the fact it introduces bias.)
The best names would be inclusiveLowerBound and exclusiveUpperBound but some people might think that’s a bit long. :P
In fact all of C++'s fancy random number classes do it, and I dare say it does make more sense to do it that way.
Unfortunately in this case the random function exists in an attempt to be compatible with Arduino, so we have to go with what they chose.
@FManga knows, he was just giving a real world example (that’s what asterocks actually does sadly).
I admire your battle against ‘magic numbers’ though.
Personally I say prefer const and constexpr const over #define because #define pollutes the whole code among other issues.
I guess it’s just the name that’s wrong. I did see the exclusive upper bound somewhere haha
But that means for rolling a dice, you’d have to do random(1, 7), which sounds weird to me. Well, usages being usages, that’s OK as long as the final stuff is consistent and working, I guess!
(I do prefer const/constexpr myself, and I rely on preproc only when I can’t do something in c++ or templates haha)
I know, but like I say, it’s because of how the calculation is done. random(1, 7) translates to 1 + random() % (7 - 1) (i.e. min + random() % (max - min)).
You’re a cat after my own heart. :P
I know it was probably written by someone inexperienced, but stuff like that always hurts ; n ;.
Depends how it’s actually implemented.
I think the actual random number generation function is pre-compiled.
It’s marked extern and I’ve never found the source code for it.