Peculiarities of the strtol() Function

Imagine my disappointment to learn that the atoi() function, one of the first I learned in C, is actually a macro. I’m horrified. As much as I treasure converting strings to integers, I shall survive this life-changing discovery.

The strtol() function most likely stands for string-to-long It’s prototyped in the stdlib.h header file. Here’s the man page format:

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

The str argument is the string containing the number to convert. The endptr argument helps determine whether the str string contained zero or was empty. And base sets the way the input value is interpreted as base 10, 8, or 16.

Here’s some sample code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char x[] = "123456";
    char y[] = "003224";
    char z[] = "0xA72B";
    int a,b,c;

    a = strtol( x, NULL, 10);
    b = strtol( y, NULL, 8);
    c = strtol( z, NULL, 16);

    printf("%s in base 10: %d\n",x,a);
    printf("%s in base 8: %o\n",y,b);
    printf("%s in base 16: %x\n",z,c);

    return(0);
}

The three string values in arrays x, y, and z are expressed in bases 10, 8, and 16, respectively. The three strtol() functions convert each value; the NULL pointer means that the endptr argument is ignored. And the values returned are displayed in their proper formats. Here’s the output:

123456 in base 10: 123456
003224 in base 8: 3224
0xA72B in base 16: a72b

For most purposes, the strtol( x, NULL, 10) format of the statement is used, which converts the string referenced by variable x into a decimal value. In fact, this is the atoi() macro defined in the stdlib.h header file:

(int)strtol(str, (char **)NULL, 10);

Sneaky.

The strtol() function is far more powerful than that old atoi() function, which makes it even more valuable and definitely the conversion function you want to use for potentially pesky input values. I expand on some if its input-error detection techniques in next week’s Lesson.

Leave a Reply