We get what you mean, but a clearer way of saying it is that "In C++, the index of the first element of an array is 0, not 1 as in some other programming languages".
We get what you mean, but a clearer way of saying it is that "In C++, the index of the first element of an array is 0, not 1 as in some other programming languages".
the programmer does have one flaw.
he should say
const int act_size = 9;
const char *activities[act_size] …
and rand()%act_size;
its the same, but a sized to data array mixed with a magic number to process it is asking for trouble when someone edits the code later. Maybe next year, they removed cannonball from the list:
const char *activities[] = {
"Diving",
"Lapping",
// "Cannonballing", //this was too dangerous and no longer done here
"Butterfly kicking",
"Paddling",
"Swimming",
"sidestroke",
"front crawl",
"breast stroke",
};
cout<<"We are gonna do " << activities[rand()%9]; //what happens when rand returns 8?
I don't really trust casting for this. If MAX_RAND is close to the upper limit of its type, I'd much rather do array_size(activities) && array_size(activities) - 1 <= RAND_MAX
> so that a RAND_MAX of the highest signed int won't overflow?
Since RAND_MAX is an integral constant expression,
compilers would generate a warning if there is an integer overflow.
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <limits>
int main()
{
constint rand_max = std::numeric_limits<int>::max() ;
// GNU: *** warning: integer overflow in expression of type 'int' results in '-2147483648'
// LLVM: *** warning: overflow in expression; result is -2147483648 with type 'int'
// Microsoft: *** warning: '+': integral constant overflow
constint k = rand_max + 1 ;
return k == 0 ;
}