Reading history

Command Line Arguments in C: argc and argv

5 min read 0 views

Learn command line arguments in C with argc and argv, quoting, converting arguments with strtod, usage messages on stderr, and EXIT_SUCCESS/EXIT_FAILURE.

Many programs take their input when they start rather than asking for it afterwards: gcc file.c -o app or cp a.txt b.txt. In C these command line arguments arrive in main through two parameters, argc and argv. This lesson shows how they work, how to convert them to numbers safely, and how to report errors with exit codes, by building a small command-line calculator.

In this lesson you will learn

  • The meaning of argc and argv
  • How quoting affects arguments
  • Converting arguments to numbers with strtod
  • Printing usage messages to stderr
  • Returning EXIT_SUCCESS and EXIT_FAILURE

This lesson builds on the main function in C.

argc and argv

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("argc = %d\n", argc);
    for (int i = 0; i < argc; i++)
        printf("argv[%d] = \"%s\"\n", i, argv[i]);
    printf("argv[argc] is %s\n", argv[argc] == NULL ? "NULL" : "not NULL");
    return 0;
}

Compile and run it with three arguments:

gcc -Wall -Wextra -o args args.c
./args hello "Dhaka city" 42

Output

argc = 4
argv[0] = "./args"
argv[1] = "hello"
argv[2] = "Dhaka city"
argv[3] = "42"
argv[argc] is NULL
  • argc (argument count) is the number of strings, including the program name itself, so it is 4 here.
  • argv (argument vector) is an array of strings. argv[0] is the program name as it was typed; the real arguments start at argv[1].
  • The shell splits arguments on spaces. Quotes keep "Dhaka city" together as one argument.
  • Every argument is a string, even 42. Convert it before doing arithmetic.
  • The standard guarantees argv[argc] is NULL, which allows looping until a null pointer.

A Command-Line Calculator

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

int main(int argc, char *argv[]) {
    if (argc != 4) {
        fprintf(stderr, "usage: %s <number> <+|-|x|/> <number>\n", argv[0]);
        return EXIT_FAILURE;
    }
    char *end;
    double a = strtod(argv[1], &end);
    if (*end != '\0') { fprintf(stderr, "bad number: %s\n", argv[1]); return EXIT_FAILURE; }
    double b = strtod(argv[3], &end);
    if (*end != '\0') { fprintf(stderr, "bad number: %s\n", argv[3]); return EXIT_FAILURE; }

    const char *op = argv[2];
    double r;
    if (strcmp(op, "+") == 0)      r = a + b;
    else if (strcmp(op, "-") == 0) r = a - b;
    else if (strcmp(op, "x") == 0) r = a * b;
    else if (strcmp(op, "/") == 0) {
        if (b == 0) { fprintf(stderr, "division by zero\n"); return EXIT_FAILURE; }
        r = a / b;
    } else { fprintf(stderr, "unknown operator: %s\n", op); return EXIT_FAILURE; }

    printf("%g %s %g = %g\n", a, op, b, r);
    return EXIT_SUCCESS;
}
./calc 12 x 4
./calc 7.5 / 2
./calc 10 / 0; echo "exit status: $?"
./calc 5 + abc; echo "exit status: $?"
./calc; echo "exit status: $?"

Output

12 x 4 = 48
7.5 / 2 = 3.75
division by zero
exit status: 1
bad number: abc
exit status: 1
usage: ./calc <number> <+|-|x|/> <number>
exit status: 1
  • The program first checks argc. With the wrong number of arguments it prints a usage line, the standard way command-line tools explain how to call them.
  • strtod converts text to a double and sets end to the first character it could not use. If *end is not the end of the string, the argument was not a valid number. (See String to Number Conversion.)
  • Error messages go to stderr with fprintf, so they still appear on screen when normal output is redirected to a file.
  • return EXIT_FAILURE; gives exit status 1, which scripts can test with $? in bash or %ERRORLEVEL% on Windows. Success returns 0.
  • x is used for multiplication because the shell would expand an unquoted * into a list of file names.

Common Mistakes

  1. Reading argv[1] without checking argc, which crashes when no argument is given.
  2. Using atoi, which silently returns 0 for invalid input.
  3. Comparing strings with ==; use strcmp(argv[1], "-h") == 0.
  4. Modifying string literals through argv copies; the argv strings themselves may be modified, but literals you assign elsewhere may not.

Practice Exercises

Exercise 1. Write a program that prints the sum of all integer arguments, for example ./sum 4 5 6 prints 15.

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

int main(int argc, char *argv[]) {
    long total = 0;
    for (int i = 1; i < argc; i++)
        total += strtol(argv[i], NULL, 10);
    printf("%ld\n", total);
    return 0;
}

Exercise 2. Add a -h option to the calculator that prints the usage line and exits with success.

Show answer
if (argc == 2 && strcmp(argv[1], "-h") == 0) {
    printf("usage: %s <number> <+|-|x|/> <number>\n", argv[0]);
    return EXIT_SUCCESS;
}

Frequently Asked Questions

How do I pass arguments when running from an IDE?

Most IDEs have a run configuration setting called “program arguments” or “command line arguments”. In VS Code, set “args” in launch.json; in Code::Blocks, use Project > Set programs’ arguments.

How do professional tools parse options like -v or –output?

On Linux and macOS, the POSIX getopt function (and GNU getopt_long) handles short and long options, combined flags and option values for you.

Summary

  • argc counts the arguments; argv holds them as strings, with the program name in argv[0].
  • Always check argc before reading argv.
  • Convert with strtol/strtod and validate the result.
  • Report errors on stderr and return EXIT_FAILURE.

Next: void, NULL and Dangling Pointers.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *