Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

strtol — convert text to long

strtol reads a long integer from the beginning of text. Check endptr and errno to detect errors and any unconsumed suffix.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <stdlib.h>
long int strtol(const char *restrict nptr, char **restrict endptr, int base);

strtol from <stdlib.h> skips leading whitespace, accepts an optional + or -, and converts digits to long.

base must be 0 or 2–36. 0 detects decimal, octal (0), hexadecimal (0x), and, in C23, binary (0b). Explicit bases 16 and 2 allow their respective prefixes. A C23 compiler flag does not attest runtime-library support.

If endptr != NULL, *endptr points to the first unconsumed character. No conversion returns 0 with *endptr == nptr; 0 alone does not indicate failure.

Set errno = 0 before calling. An out-of-range value returns LONG_MIN or LONG_MAX and sets ERANGE. If endptr != NULL and complete consumption is required, also check **endptr == '\0': compare the character pointed to by *endptr, not the pointer itself, with the string terminator. In the C locale, trailing whitespace remains unconsumed. In other locales, additional locale-specific input forms may be accepted. Reaching the terminator confirms that the entire string was consumed, not that the input matched the C locale’s grammar.

Examples

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

int main(void)
{
    const char *text = "123";
    char *end;
    errno = 0;
    long value = strtol(text, &end, 10);

    if (end == text) {
        puts("no digits");
        return EXIT_FAILURE;
    }
    if (errno == ERANGE) {
        puts("out of range");
        return EXIT_FAILURE;
    }
    if (*end != '\0') {
        puts("trailing characters");
        return EXIT_FAILURE;
    }
    printf("value=%ld\n", value);
    return EXIT_SUCCESS;
}

Result

value=123

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources