Because C++ is deliberately vague about the minimum and maximum sizes of primitive types like int
, big integer literals like 2100000000000000000000000
are dangerously platform-dependent.
Your program may even be ill-formed and not compile at all as a result of it. Fortunately, checking user input does not have anything to do with integer literals. The former occurs at runtime, the latter is a compile-time aspect.
This means that your example code is an unrealistic scenario. In a real program, the value of g1
will not be a compile-time constant but a number entered by the user.
A very good practice is to first let the user enter the number into a std::string
with std::getline
, and then use std::stoi
to convert the string into an int
.
If you follow that practice, all error checking is performed by the standard library and you don't have to use INT_MIN
, INT_MAX
or their C++ counterparts std::numeric_limits<int>::min()
and std::numeric_limits<int>::max()
at all.
Example:
#include <iostream>
#include <string>
auto const text = " year";
auto const text2 = " age";
int main() {
try {
std::string input;
std::getline(std::cin, input);
auto const g1 = std::stoi(input);
std::getline(std::cin, input);
auto const g2 = std::stoi(input);
std::cout << g1 << text;
std::cout << g2 << text2;
std::cout << '\n';
} catch (std::out_of_range const&) {
std::cout << "Please enter an integer\n";
}
}
The great thing is that this will also detect other kinds of bad user input, for example when the user enters letters instead of digits. Extending the error handling in this piece of example code to catch other kinds of exceptions is left as an exercise to the reader.