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.