Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Minor word smithing

The process of parsing an integer or floating-point number from a string can produce many errors. The string might not contain a number. It might contain a number of the correct type that is out of range (such as an integer that is larger than INT_MAX). The string may also contain extra information after the number, which may or may not be useful after the conversion. These error conditions must be detected and addressed when a string-to-number conversion is performed using standard C library functionsa C Standard Library function.

The strtol(), strtoll(), strtoul(), strtoull(), strtof(), strtod(), and strtold() functions convert the initial portion of a null-terminated byte string to long int, long long int, unsigned long intunsigned long long int, float, double, and long double representation, respectively.

Use strtol() or a related function Use one of the C Standard Library strto*() functions to parse an integer out of a string. Likewise, use strtof() or a related function to parse a or floating-point number from a string. These functions provide more robust error handling than alternative solutions. Also, use the strtol() function to convert to a smaller signed integer type such as signed int, signed short, and signed char, testing the result against the range limits for that type. Likewise, use the strtoul() function to convert to a smaller unsigned integer type such as unsigned int, unsigned short, and unsigned char, and test the result against the range limits for that type. These range tests do nothing if the smaller type happens to have the same size and representation on for a particular compilerimplementation.

Noncompliant Code Example (atoi())

...