Do I need to cast the result of strtol to int?

Michael Kristofik picture Michael Kristofik · Mar 11, 2010 · Viewed 7.3k times · Source

The following code does not give a warning with g++ 4.1.1 and -Wall.

int octalStrToInt(const std::string& s)
{    
    return strtol(s.c_str(), 0, 8);
}

I was expecting a warning because strtol returns a long int but my function is only returning a plain int. Might other compilers emit a warning here? Should I cast the return value to int in this case as a good practice?

Answer

Šimon Tóth picture Šimon Tóth · Mar 11, 2010

Best approach is:

long x = strtol(...); assert(x <= INT_MAX); return (int)x;

You need limits.h and assert.h