Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why shouldn't I use atoi()? [duplicate]

Tags:

c

Someone told me that I shouldn't use atoi(), and that I should always use strtol() instead. What's wrong with atoi() that I shouldn't use it? Is strtol() really the right thing to use instead? (And what about the fact that strtol() returns a long, not an int like atoi() does?)

like image 729
This isn't my real name Avatar asked Jul 17 '13 20:07

This isn't my real name


People also ask

Is atoi deprecated?

The atoi, atof, and atol functions are a part of the ISO standard C library (C89), while the atoll function is added by C99. However, because of the ambiguity in returning 0 and lack of thread-safety and async-cancel safety on some operating systems, atoi is considered to be deprecated by strtol.

What does atoi return if not a number?

The atoi() function returns an int value that is produced by interpreting the input characters as a number. The return value is 0 if the function cannot convert the input to a value of that type.

Does atoi ignore newline?

Synopsis. The atoi() function converts a string of characters representing a numeral into a number of int . Similarly, atol() returns a long integer, and in C99, the atoll() function converts a string into an integer of type long long . The conversion ignores any leading whitespace characters (spaces, tabs, newlines).


2 Answers

from your own link:

The atoi() function is subsumed by strtol() but is retained because it is used extensively in existing code. If the number is not known to be in range, strtol() should be used because atoi() is not required to perform any error checking.

Or

atoi is obsolete

like image 60
Sam I am says Reinstate Monica Avatar answered Sep 22 '22 06:09

Sam I am says Reinstate Monica


If string will be much large and can't be converted, it causes undefined behaviour as value of that string can be too large and that may not be in range. In such cases(where number is not known to be in range) strtol() should be used.

like image 36
Shumail Avatar answered Sep 21 '22 06:09

Shumail