Embedded Artistry libc
C Standard Library Support for Bare-metal Systems
atoi.c File Reference
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
Include dependency graph for atoi.c:

Go to the source code of this file.

Functions

int atoi (const char *str)
 Interprets an integer value in a byte string pointed to by str. More...
 

Function Documentation

◆ atoi()

int atoi ( const char *  str)

Interprets an integer value in a byte string pointed to by str.

Interprets an integer value in a byte string pointed to by str. Discards any whitespace characters until the first non-whitespace character is found, then takes as many characters as possible to form a valid integer number representation and converts them to an integer value. The valid integer value consists of the following parts: a) (optional) plus or minus sign b) numeric digits

Parameters
strpointer to the null-terminated byte string to be interpreted
Returns
Integer value corresponding to the contents of str on success. If the converted value falls out of range of corresponding return type, the return value is undefined. If no conversion can be performed, ​0​ is returned.

Definition at line 5 of file atoi.c.

6 {
7  bool neg = false;
8  int val = 0;
9 
10  switch(*str)
11  {
12  case '-':
13  neg = true;
14  // intentional fallthrough to advance str
15  case '+':
16  str++;
17  }
18 
19  while(isdigit(*str))
20  {
21  val = (10 * val) + (*str++ - '0');
22  }
23 
24  return (neg ? -val : val);
25 }
int isdigit(int ch)
Checks if the given character is a numeric character.
Definition: isdigit.c:5

References isdigit().