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.
errnodeclared as a local variable?strtolis totally broken. Don’t use it! In particular, it’s not required thaterrnois set if the conversion was unsuccessful because a non-numerical value was passed to it (e.g."xyz"). Luckily, some implementations still seterrnounder these circumstances but it’s not required, the function could just fail silently.strtolis required to setendto the address passed into it, even if internally, it has skipped some leading space, etc. So it's possible to detect this condition as well.