atoi() — string to int

atoi is not deprecated, your source is incorrect. Nothing in the current C standard ISO 9899:2011 indicates this (see for example chapter 6.11 future language directions), nor anything in earlier standards.

As per the C standard, atoi is equivalent to strtol as follows, C11 7.22.1.2:

The atoi, atol, and atoll functions convert the initial portion of the string pointed to by nptr to int, long int, and long long int representation, respectively.

Except for the behavior on error, they are equivalent to

atoi: (int)strtol(nptr, (char **)NULL, 10)

atol: strtol(nptr, (char **)NULL, 10)

atoll: strtoll(nptr, (char **)NULL, 10)

strtol is preferred, as atoi invokes undefined behavior upon error. See 7.22.1 "If the value of the result cannot be represented, the behavior is undefined."


It does say on Apple's Mac OS X Manual Page for atoi(3) (and in the BSD man pages too) that atoi has been deprecated.

The atoi() function has been deprecated by strtol() and should not be used in new code.

I would use the strtol() equivalent just for that reason, but i doubt you have to worry about atoi() being removed.

from http://www.codecogs.com/library/computing/c/stdlib.h/atoi.php Implementation Notes

* The atoi function is not thread-safe and also not async-cancel safe.
* The atoi function has been deprecated by strtol and should not be used in new code.


The description of atoi() has one very important point in relation to the similarities/differences to strtol()

> ... The call atoi(str) shall be equivalent to:
> (int) strtol(str, (char **)NULL, 10)
> except that the handling of errors may differ.

Try this for fun:

const char *buf = "forty two";
int t1 = atoi(buf);             /* detect errors? */
int t2 = strtol(buf, NULL, 10); /* detect errors? */


No, you shouldn't use the above instead of atoi.

You should actually check the error information that strtol makes available:

i = atoi(s);

should be replaced by

char* stopped;
i = (int)strtol(s, &stopped, 10);
if (*stopped) { /* handle error */ }