Saiteja Pabisetti
Saiteja Pabisetti

Reputation: 109

usage difference between "atoi" and "strtol" in c

I have been using atoi for a year now and I have an issue in the recent days that the expression:

atoi("20") is giving a value of 0 as output.

When I Google'd the issue I found that it is deprecated and strtol should be used instead.

The interesting point I came to know is atoi internally uses strtol. So, how can the issue be solved when I change it to strtol?

Upvotes: 8

Views: 14483

Answers (3)

Lundin
Lundin

Reputation: 213842

In addition to this answer by pmg that explains how strto... has more functionality and error checking, the ato... functions are guaranteed by the standard to behave like this (C17 7.22.1.2):

Except for the behavior on error, they are equivalent to

atoi:  (int)strtol(nptr, (char **)NULL, 10)
atol:  strtol(nptr, (char **)NULL, 10)
atoll: strtoll(nptr, (char **)NULL, 10)

That being said, ato... are not required to call strto... internally (though this is the case in many libs), just to behave identically save for the error handling.

Please note that the ato... functions are not formally listed as obsolete yet. But they should be avoided still, mainly because it is pointless to use atoi when we can as well use strtol(str, NULL, 10), the latter being identical but with better error handling.

Upvotes: 0

Hitokiri
Hitokiri

Reputation: 3699

The explication from man page:

The atoi() function converts the initial portion of the string pointed to by nptr to int. The behavior is the same as:

strtol(nptr, NULL, 10);

except that atoi() does not detect errors. The atol() and atoll() functions behave the same as atoi(), except that they convert the initial portion of the string to their return type of long or long long.

For more infos, you can see the difference of two functions in this topic atoi - strtol

Upvotes: 10

pmg
pmg

Reputation: 108938

Depending on the data, strtol() has greater functionality

int easy = atoi(data);
// no errors detected

char *err;
errno = 0;
long tmp = strtol(data, &err, 10);
if (errno) /* deal with errno: overflow? */;
if (tmp > INT_MAX) /* int overflow */;
if (tmp < INT_MIN) /* int "underflow" */;
if (*err) /* extra data */;
int comprehensive = tmp; // convert from long

Upvotes: 4

Related Questions