Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

atoi() — string to int

Tags:

c

I read that atoi() is deprecated and that it is equivalent to:

(int)strtol(token_start, (char **)NULL, 10);

Does that mean I should use the above instead of atoi(chr) or is it just saying they are equivalent?

like image 672
user105033 Avatar asked Sep 28 '09 18:09

user105033


3 Answers

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."

like image 144
Lundin Avatar answered Nov 17 '22 19:11

Lundin


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.

like image 8
John Boker Avatar answered Nov 17 '22 20:11

John Boker


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? */

like image 4
pmg Avatar answered Nov 17 '22 19:11

pmg