year
is an
int.
Why was there no output?
if (year < INT_MAX) {
return EXIT_FAILURE;
}
year
and
distance_yrs
are
ints.
Why does this fail to check for overflow?
if (year + distance_yrs < INT_MAX) {
year += distance_yrs;
} else {
cerr << "Can't go beyond year " << INT_MAX << "\n";
return EXIT_FAILURE;
}
We saw last week how to check for overflow before addition.
char alphabet(int a)
{
char alpha[26] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
if (a < 0 || a >= 26) {
cerr << "Argument " << c <<
" must be in range 0 to 26.\n";
exit(EXIT_FAILURE);
}
return alpha[a];
}
Use
size_t
for array subscripts:
it simplifies the error checking.
No need to write the 26.
Make the array
const.
We saw
static.C
on October 8th.
char alphabet(size_t a)
{
static const char alpha[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
static const size_t n = sizeof alpha / sizeof alpha[0];
if (a >= n) {
cerr << "Argument " << c <<
" must be in range 0 to " << n << ".\n";
exit(EXIT_FAILURE);
}
return alpha[a];
}
Easier to create an array of 27 characters,
ending with an unused character of
'\0'.
char alphabet(size_t a)
{
static const char alpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
static const size_t n = sizeof alpha / sizeof alpha[0] - 1;
if (a >= n) {
cerr << "Argument " << c <<
" must be in range 0 to " << n << ".\n";
exit(EXIT_FAILURE);
}
return alpha[a];
}