I've been trying to properly convert a char array to a long with strtol
, check if there was an overflow or underflow and then do an int cast on the long. Along the way, I've noticed a lot of code that looks like this
if ((result == LONG_MAX || result == LONG_MIN) && errno == ERANGE)
{
// Handle the error
}
Why can you not just say
if(errno == ERANGE)
{
// Handle the error
}
From my understanding, if an underflow or overflow occur, errno is set to ERANGE in both cases. So is the former really necessary? Could checking ERANGE alone be problematic?
This how my code looks as of now
char *endPtr;
errno = 0;
long result = strtol(str, &endPtr, 10);
if(errno == ERANGE)
{
// Handle Error
}
else if(result > INT_MAX || result < INT_MIN)
{
// Handle Error
}
else if(endPtr == str || *endPtr != '\0')
{
// Handle Error
}
num = (int)result;
return num;
If there is a reason for the former please let me know.
LONG_MAX/LONG_MIN
andERANGE
. Apart from the fact that the man page shows that as an example. The only sensible use case I can think of is to differentiate between overflow and underflow. I too would be interested to hear whether there are other reasons. – Grammarerrno != 0 && result == 0
. Though to be honest, I'm not sure what could cause that because if strtol returns a 0, then I'm positive strtol does not set errno to anything assuming it was initially set to zero. – Travisif(errno)
– Monogamist