← The C Language Lesson 68 of 77 · 10 XP

Command-line arguments

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Programs in Linux get parameters right when they're started: ls -l /home, gcc main.c -o main. In C they arrive in main:

int main(int argc, char *argv[])
{
    // argc — how many arguments (including the program's name)
    // argv[0] — the program's name, argv[1]… — the arguments, argv[argc] == NULL
    for (int i = 0; i < argc; i++)
        printf("argv[%d] = %s\n", i, argv[i]);
    return 0;
}
$ ./main hello 42
argv[0] = ./main
argv[1] = hello
argv[2] = 42

All the arguments are strings. A number has to be converted: atoi(argv[2]), or more reliably strtol.

A good program checks argc and prints a usage hint:

if (argc != 3) {
    fprintf(stderr, "usage: %s <word> <count>\n", argv[0]);
    return 1;
}

The tests in this lesson start the program with arguments: in the "Input" field, the first line $ ./main … is the command that starts it.

Task. A mini calculator: ./main 2 + 3 prints 5. Support +, - and x (multiplication: a * character in the terminal would expand into file names). If there aren't three arguments, print usage: main A OP B.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.