errno
is an old C hack. It's a global variable (today thread local).
strtol
sets it to a non-zero value if there is a (detected) error (and
unchanged if there is no error, or if its original value wasn't
0—it's designed so that you can enchain a number of calls, and
only check at the end).
Note that the code in question is wrong. (I know because I recently
made the same error. The semantics of strtol
in case of error are
strange, to put it mildly.) You need something like:
bool
intValue( std::string const& token, int& toReturn )
{
char* end = NULL;
char const* s = token.c_str();
errno = 0;
long results = strtol( s, &end, 10 );
bool error = errno != 0
|| end != s
|| *end == '\0'
|| results <= std::numeric_limits<int>::max()
|| results >= std::numeric_limits<int>::min();
if ( !error ) {
toReturn = results;
}
return error;
}
Note that 1) you have to ensure that end != s
; and 2) you have to
range check if the results are to be written to an int
. WRT the
first, the specification of strtol
says that if it doesn't find any
characters to convert (i.e. the string doesn't contain any digits), it
returns 0, sets end
to the beginning of the string, and doesn't modify
errno
.