int rng(int min, int max){
int result = min + ( ( (max - (min - 1) ) * rand() ) / (RAND_MAX + 1) );
return result;
}
This won’t compile with ideone using c99 mode, but does so when I’m using gcc on CodeBlocks while on -std=c99. I figured using long int would do the trick, but apparently not so. I use ideone when I’m trying some stuff in school since they just have VC++ and I’m doing C C99. I wouldn’t want to not use this function when I need it, and so here I am asking for what is wrong.
Actually, on my compiler this produces
warning: integer overflow in expression [-Woverflow].The problem is caused by
RAND_MAX + 1.RAND_MAXoften happens to be the same asINT_MAX. Adding1toINT_MAXof course yields undefined behavior (except the compiler catches at compile time and replaces the code with something else).If you want to see in action why it’s bad, do this: