atoi is a C standard library function that converts strings to numbers (more specifically, integers).
const char *str
The function receives one parameter, a string. Note that the string is received as a constant - the function
atoi will never alter a received string; only return its converted integer value.
ASIDE - STRING REFRESHER
When working with strings in C, remember - strings are no more than arrays of ASCII-encoded characters ending with a terminating null byte (
If the received string can be successfully converted to a number, the function returns the converted integer. Otherwise, it returns
What exactly is a string that can be successfully converted to a number? Well, it turns out that the behavior here is a bit funky.
In general, strings that can successfully be converted to numbers strictly include the following:
- Strings consisting exclusively of ASCII digits
- Strings consisting exclusively of ASCII digits and starting with the character
- Strings consisting exclusively of ASCII digits and starting the with character
However, this does not mean that you will receive
0 for any other kind of string passed to
atoi works incrementally; in other words, it builds numbers represented by strings one-by-one, iterating over characters from left to right. Only upon encountering a non-ASCII digit (assuming it is not a
'-' at the beginning of the string), does the function break.
atoi returns one of two possible values - if the function is at the beginning of the string and has not converted any values, it returns
0. Otherwise, it returns the current number it has built thus far.
In briefer summation, a more proper description of atoi’s return value is the first valid number that can be converted from the received string, or
atoi is declared as follows:
* atoi - Converts a string to an integer.
* @str: The string to convert.
* Return: The int value of the first valid number that can be converted from @str.
* Otherwise, 0.
int atoi(const char *str);