Rewrite C Function: atoi

Last Updated : 10 July, 2022 · 5 min read

articles banner image

Today we are going to discuss the atoi function in the C programming language. We are going to take a close examination of this function. For the reader's convenience, we divided this tutorial into four parts.

Structure of atoi:

Declaration: int atoi(const char *str);

Return: integer value of the source character array. 0 in case of invalid source array.

Parameter list:
(const char *str) - the source character array that represents an integer value (e.g. "123").

Header file: <stdlib.h>.

1. So, what is atoi?

Atoi is a function that returns the first occurrence of an integer in a string. In cases when conversion to integer is not possible, this function returns 0. If we were to call atoi("123abc"), for example, this function would return to us an integer with a value of 123.

Note: atoi also converts and returns negative integer values.

The function atoi is defined in the <stdlib.h> library. This means that for us to use this function, we need to include the header file into our program (e.g. #include <stdlib.h>).

Example 1: usage the atoi function in C.

# include <stdlib.h>

int main ( void )
{
    
atoi( "-12a3" ); //returns -12
    
return 0 ;
}

2. And how to rewrite atoi function in C?

To rewrite atoi function accurately, we will break it down into three smaller parts.

2.1. Skipping white space characters

Consider the code below for a second:

Example 2:

# include <stdio.h>

int main ( void )
{
    
char *string = "\n\t100" ;
    
int i = 0 ;
    
while (string[i] == 32 || (string[i] >= 9 && string[i] <= 13 ))
        
i++;
    
printf ( "i = %d", i);
    
return ( 0 );
}

Possible output:

i = 2

In the code snippet above, we loop through a string variable until a non-whitespace character is found. In this case string contains two whitespace characters (\n and \t) at the start of an array. For this reason while loop (on line 6) executes two times, which is indicated by i = 2.

2.2. Checking if an integer value is negative

Now that a non-whitespace character is found, we can check if it is a minus.

Example 3:

int minus = 1 ;
if (string[i] == '-' || string[i] == '+' )
{
    
if ( string[i] == '-' )
        
minus = - 1 ;
    
i++;
}

Here we have two if blocks. In the first block (on line 2), we check for both plus and minus signs and increment our i variable by one (on line 6).

In the second if block (on line 4) we check specifically if the sign is a minus. In which case we set our minus flag to -1 for later use.

Note: atoi returns 0 if there is a space after a plus or a minus sign in a string.

2.3. Converting char values to digits

Lastly but not leastly, we get the integer value. For this to be achieved, we use the formula below:

Example 4:

int val = 0;
while ( string[i] >= 48 && string[i] <= 57 )
{
    
val = val * 10 + ( string[i] - 48 );
    
i++;
}

For a less experienced programmed this code might initially cause a bit of confusion. To better illustrate what is actually happening, we can consider the following example.

Let's say str = "321". For each character our loop (on line 2) would be executed once. Hence it would make 3 iterations:

First iteration: val * 10 + (string[i] - 48); // 0 + 3
Second iteration: val * 10 + (string[i] - 48); // 3 * 10 + 2
Third iteration: val * 10 + (string[i] - 48); // 32 * 10 + 1

As you can see string[i] char value is converted to a numerical value, which, in turn, is its ASCII value. Hence '3' is converted to 51, '2' to 50 and '1' to 49.

Same type conversion happens in the while loop, too (on line 2). Meaning that the loop is executed until the non numerical value is met. Another way to check for the same condition would be with an isdigit function.

Now that we have all the necessary components of our atoi function, let's combine everything together and return the converted value.

Example 5: rewritten atoi function in C.

int our_atoi ( const char *string )
{
    
int i = 0 ;
    
while (string[i] == 32 || (string[i] >= 9 && string[i] <= 13 ))
        
i++;
    
int minus = 1 ;
    
if (string[i] == '-' || string[i] == '+' )
    
{
        
if ( string[i] == '-' )
            
minus = - 1 ;
        
i++;
    
}
    
int val = 0 ;
    
while (string[i] >= 48 && string[i] <= 57 )
    
{
        
val = val * 10 + (string[i] - 48 );
        
i++;
    
}
    
return (val * minus);
}

Depending on the value of minus variable (1 or -1), returned integer will be positive or negative.

3. What is a way to improve the atoi function?

One way to improve the atoi function in C would be to protect it against segmentation faults. Passing a NULL pointer as an argument atoi(NULL) causes a segmentation fault. This is because the string is being accessed without checking for a NULL pointer.

As a way to actually protect against segmentation faults you could insert the following two lines of code at the very top of our_atoi function (insert on line 3):

if (string == NULL)
    return 0;

With these lines of code, a NULL pointer would not cause a segmentation fault. The function would simply return 0.

4. Quiz of the atoi function knowledge

Quiz : Rewritten atoi function in C

1What would atoi("-2-1") return?

2In which C library is the atoi function included?

3Passing a NULL pointer to the atoi function,

quiz completed!

Congrats!

Feel free to share your achievement below!