Reading C command-line values and validating program arguments with argc, argv, and strtol.

Command Line Arguments in C: Read and Check a Number

A program launched with a value such as 42 receives text, not an integer ready for arithmetic. To handle C command-line inputs safely, check how many values arrived, then convert the intended string and inspect the conversion result.

Arguments in C Programs: Read argc and argv

A hosted C program can define main with int argc and char *argv[]. argc counts the entries supplied to the program, including the program name when it is available. argv points to an array of character pointers; each ordinary entry points to a null-terminated string. The entry argv[argc] is a null pointer marking the end of the array.

For a typical invocation ./number 42, argc is 2, argv[0] is ./number, and argv[1] is 42. The exact text of the program name depends on how it was invoked and can be unavailable on some implementations. Check the count before accessing the next entry: when no value is supplied, argv[1] is the terminating null pointer, not a number string.

The following program accepts exactly one decimal integer and reports invalid input:

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

int main(int argc, char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "Usage: number INTEGER\n");
        return EXIT_FAILURE;
    }

    char *end;
    errno = 0;
    long value = strtol(argv[1], &end, 10);
    if (end == argv[1] || *end != '\0' || errno == ERANGE) {
        fprintf(stderr, "Invalid integer: %s\n", argv[1]);
        return EXIT_FAILURE;
    }

    printf("Value: %ld\n", value);
    return EXIT_SUCCESS;
}

On a system with a C compiler, save it as number.c and compile it with warnings enabled:

cc -std=c11 -Wall -Wextra -o number number.c
./number 42
./number -7

The first run prints Value: 42; the second prints Value: -7. Shell syntax and the executable name may differ on your system. A C program receives command-line parameters after the shell has split the command into words. Quote a value containing spaces when it must arrive as one entry; for this numeric example, quoted trailing spaces are rejected by the conversion check. Do not treat a supplied string as a trusted array index without checking its numeric range. These command line arguments in C remain strings until the program converts them. The GNU C manual describes the count and array.

Check the Conversion

strtol converts the initial portion of a string to a long. The final argument 10 selects decimal input. The function accepts leading whitespace and an optional sign. The example rejects any trailing characters, including trailing whitespace, because *end must be the string terminator. Choose a different policy deliberately if your application needs to accept surrounding whitespace.

The three checks serve distinct purposes:

  • end == argv[1] means no digits were converted, as with an empty string or abc.
  • *end != '\0' detects a leftover suffix, as in 42cats.
  • errno == ERANGE detects a result outside the range of long.

Set errno to zero before calling strtol, since a successful conversion does not have to clear an earlier error. A return value of zero alone is ambiguous: it can represent valid input 0 or a failed conversion. If the destination is an int, also compare the resulting long against INT_MIN and INT_MAX from <limits.h> before casting.

Try Missing and Invalid Values

Run ./number without a value or supply two values to see the usage message. With ./number 42cats, conversion stops at c, so the program prints an error and exits with failure. A very large decimal string may exceed the available range and is rejected as well.

The most likely input mistake is passing a missing or nonnumeric value. Recognize it from the usage or invalid-integer message, then supply exactly one whole decimal number, such as ./number 42, and run the program again.