Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.8k views
Welcome To Ask or Share your Answers For Others

1 Answer

strtol provides you with more flexibility, as it can actually tell you if the whole string was converted to an integer or not. atol, when unable to convert the string to a number (like in atol("help")), returns 0, which is indistinguishable from atol("0"):

int main()
{
  int res_help = atol("help");
  int res_zero = atol("0");

  printf("Got from help: %d, from zero: %d
", res_help, res_zero);
  return 0;
}

Outputs:

Got from help: 0, from zero: 0

strtol will specify, using its endptr argument, where the conversion failed.

int main()
{
  char* end;
  int res_help = strtol("help", &end, 10);

  if (!*end)
    printf("Converted successfully
");
  else
    printf("Conversion error, non-convertible part: %s", end);

  return 0;
}

Outputs:

Conversion error, non-convertible part: help

Therefore, for any serious programming, I definitely recommend using strtol. It's a bit more tricky to use but this has a good reason, as I explained above.

atol may be suitable only for very simple and controlled cases.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...