#include <stdlib.h> int atoi(const char* s);
atoi function converts a null-terminated string to an integer.
The behaviour of
atoi is undefined if the string has a value outside of the range that can be represented by an
int. It follows that
atoi is not safe to use unless it can be shown that (by circumstance or design) such an overflow will not happen.
One way to be ensure this would be to check that the input is no more than four characters in length. The maximum possible value is then 9999, which any implementation of ISO C must be able to represent as an
For longer inputs, the effort required to exclude the possibility of overflow is likely to outweigh any convenience gained from using
atoi function does not validate its input in any way:
- Trailing non-numeric content is silently ignored.
- Inputs that do not begin with a number (even after skipping whitespace) give a result of zero.
The effect is to convert the string into an integer at any cost, even if it bears no resemblance to one. There are two problems with this behaviour:
- Erroneous inputs are silently ignored.
- Zero is assumed to be a suitable default value, which may or may not be appropriate.
These issues could be overcome by validating the input before calling
atoi, but as above the effort required to do this is likely to outweigh any convenience gained from using this function.
strtol can be used in a way that avoids the above pitfalls:
- Overflow does not invoke undefined behaviour, and is reported by setting
errnoto the value
- Erroneous inputs can be detected by checking that at least one character has been converted, and that the last such character is a digit.
- If required, it is possible to determine whether all of the input was converted by checking whether the next character is null.
- ✔ C90
- ✔ C99
- ✔ C++98
- ✔ C++11
In C++, use of the header
<stdlib.h> is deprecated in favour of
atoi should be viewed with suspicion as it is rarely justified.
-  C99 §7.20.1 ¶1
 C99 §220.127.116.11.1 ¶1 (requires that
INT_MAXbe at least +32767)
-  C99 §18.104.22.168 ¶4
-  C99 §22.214.171.124 ¶8
atollfunctions, Programming languages — C, ISO/IEC 9899:1999, §126.96.36.199, p306
atoi, The Open Group Base Specifications, Issue 7, The Open Group, 2008
atoi(3), Linux Programmer’s Manual, The Linux man-pages project
- Parsing of Integers, The GNU C Library Reference Manual, The GNU Project