When you have a choice of two functions to accomplish the same task, prefer the one with better error checking and reporting.
The following table shows a list of C standard library functions that provide limited or no error checking and reporting along with preferable alternatives:
Function | Preferable | Comments |
---|---|---|
| | No error indication, undefined behavior on error. |
| | No error indication, undefined behavior on error. |
| | No error indication, undefined behavior on error. |
| | No error indication, undefined behavior on error. |
| | No error indication, silent failure on error. |
| | No error indication, silent failure on error. |
Noncompliant Code Example (atoi()
)
...
- do not need to set
errno
on an error - have undefined behavior if the value of the result cannot be represented (see undefined behavior 113 of Annex J of C99)
- some implementations return 0 if the string does not represent an integer (which is indistinguishable from a correctly formatted, zero-denoting input string) but C99 only specifies the behavior of these functions on success.
See also MSC34-C. Do not use deprecated or obsolescent functions.
Compliant Solution (strtol()
)
...