Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Instead of these functions, try inputing the value as a string and then converting it to an integer valoue using strtol() or a related function INT00-A.

Non-Compliant Example 1

This non-compliant code example converts the string stored in the static array buff to a signed integer value using the atoi() function.

...

  • do not need to set errno on an error
  • have undefined behavior if the value of the result cannot be represented

Non-Compliant Example 2

This non-compliant example uses the sscanf() function to convert a string to an integer. The sscanf() function has the same problems as atoi().

Code Block
char buff [25];
int int_var;

fgets(buff, sizeof buff, stdin);
sscanf("%d", buff, &int_var);

Compliant Solution

The following compliant example uses strtol() to input an integer value and provides error checking to make sure that the value is a valid integer in the range of int.

...

If you are attempting to convert a string to a smaller interger type (int, short, or signed char), then you only need test the result against the limits for that type. The tests do nothing if the smaller type happens to have the same size and representation on a particular compiler.

References