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?)
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.
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.
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).
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With