atol() v/s. strtol()

Viewed 65147

What is the difference between atol() & strtol()?

According to their man pages, they seem to have the same effect as well as matching arguments:

long atol(const char *nptr);

long int strtol(const char *nptr, char **endptr, int base);

In a generalized case, when I don't want to use the base argument (I just have decimal numbers), which function should I use?

8 Answers

Though the question is old, the content is not as it is about an integral part of the language.

Other answers fail to emphasize two important detail: Both atol and strl will do the same thing but atol tries to parse only a base 10 format (signs and digits) and will give no error.

  • While strtol (and all strto_ that return integer type) can fetch a number in any base ranging from 2 to 36, all ato_ functions (atoi, atol) will fetch only base 10.

  • Both will return zero (0) if no parse is possible, yet strtol can give the location where parse is ended and an error if the number was too big/small.

side note: any strto_ or ato_ that returns a decimal number uses base 10, meaning digits and a few other characters to represent a floating-point number.

Related