SyntaxPilot
Courses/C Programming/Lesson 19

C Programming · Lesson 19 of 30 · 16 min

Command-line arguments

queued

These are the notes for C episode 19. Since episode 1, main has had empty brackets: int main(). Today you find out what can go inside them. It starts with a bill program that asks its questions with scanf and falls apart the moment nobody is sitting at the keyboard. You fix it by giving the program its input when you start it, on the command line, and you meet argc and argv. Then the traps: arguments are text (so argv[1] * argv[2] does not compile), a missing argument makes the program crash, and atoi silently turns rubbish into 0. You fix those with a usage message, an exit status and strtol, and build a command-line bill splitter. Every example below was compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13, the same command as the SyntaxPilot compiler) and run as shown. The online compiler runs your program as ./main with no arguments; the runs with arguments below were made in a real terminal (bash on Linux).

The problem: a program that keeps asking

Real-life example: five questions for one cup of chai. At rush hour the waiter asks "Which chai?", waits, "Sugar?", waits, "Size?", waits, "Here or to go?". Fine for one customer, painful for fifty. The regular customer says the whole order at once: "Masala, less sugar, to go."

Our programs so far work like the first waiter:

#include <stdio.h>

int main() {
    int price, qty;
    printf("Price? ");
    scanf("%d", &price);
    printf("Quantity? ");
    scanf("%d", &qty);
    printf("Total: Rs %d\n", price * qty);
    return 0;
}

With 250 and 4 typed as input:

Price? Quantity? Total: Rs 1000

Now the shop wants 500 bills worked out every night at 2 a.m. by a script, with nobody at the keyboard. With no input at all:

Price? Quantity? Total: Rs 1294302752

(Run it again and you get a different number, sometimes negative: -1321664704, 592543472, ...). scanf found nothing to read, so price and qty were never set, and the program multiplied whatever garbage was in that memory.

Why it failed

  • scanf asks its questions after the program has started.
  • If no person is there to answer, it reads nothing, and the variables keep garbage values.
  • A script, a timer or another program can't sit and answer questions.
  • Idea: give the program its input at the moment you start it: ./bill 250 4.

The terminal and the command line

A terminal is a window where you type commands instead of clicking icons. The line you type is the command line.

$ gcc main.c -o bill
$ ./bill 250 4
  • gcc main.c -o bill is itself a command-line program: main.c, -o and bill are its arguments. That is how you have been giving gcc instructions all along. ($ is the terminal's prompt; you don't type it.)
  • In ./bill 250 4 the first word is the program to run (./ means "in this folder"). Every other word, separated by spaces, is an argument: an extra piece of information handed to the program as it starts. So bill gets two arguments: 250 and 4.

argc and argv

Real-life example: the order slips.

At the chai stall In C
The whole order is said at the start: "Masala, less sugar, to go" The command line: ./bill 250 4
The waiter writes one word per slip and numbers them from 0; slip 0 names the counter argv[0], argv[1], argv[2]: an array of strings; argv[0] is the program's name
He writes "3 slips" on top, so nobody reads past the end argc = 3: the argument count

To receive the arguments, main takes two parameters. The operating system fills them in before main starts:

#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]);
    return 0;
}

In the SyntaxPilot online compiler (it runs ./main with nothing after it):

argc = 1
argv[0] = ./main

The same program compiled as args and run in a terminal:

$ ./args
argc = 1
argv[0] = ./args
$ ./args 250 4
argc = 3
argv[0] = ./args
argv[1] = 250
argv[2] = 4
$ ./args "masala chai" less sugar
argc = 4
argv[0] = ./args
argv[1] = masala chai
argv[2] = less
argv[3] = sugar

What to notice:

  • argc (argument count) counts the program's name too, so it is always one more than the number of arguments.
  • argv (argument vector) is an array of strings. char *argv[] means "an array of char pointers", and each pointer points to a string (episodes 9 and 11). char **argv means exactly the same thing.
  • argv[0] is the name the program was started with (./args, ./main).
  • Valid indexes are 0 to argc - 1. The slot after the last one, argv[argc], is always NULL: an end marker. (Verified: argv[argc] == NULL is true.)
  • Double quotes keep words together: "masala chai" is one argument even with a space inside. The quotes themselves are not part of the string.
  • The names argc and argv are only a convention; the types and the order are what matter. int main(void) (or int main()) is still fine when a program takes no arguments.

What argv looks like for ./bill 250 4:

argv[0] → "./bill"
argv[1] → "250"
argv[2] → "4"
argv[3] → NULL

"250" is text: the characters '2', '5', '0' (and a '\0' at the end), not the number 250.

Arguments are text: atoi

The obvious attempt:

#include <stdio.h>

int main(int argc, char *argv[]) {
    int total = argv[1] * argv[2];
    printf("Total: Rs %d\n", total);
    return 0;
}

gcc refuses:

main.c: In function 'main':
main.c:4:25: error: invalid operands to binary * (have 'char *' and 'char *')
    4 |     int total = argv[1] * argv[2];
      |                 ~~~~~~~ ^ ~~~~~~~
      |                     |         |
      |                     char *    char *

You can't multiply two pieces of text. (With + the message is the same: invalid operands to binary + (have 'char *' and 'char *').)

The fix is atoi from <stdlib.h> (the standard library header): it turns text into an int.

  • atoi("250") → 250. The name means ASCII to integer; ASCII is the code that stores characters as numbers.
  • It reads digit characters from the start of the text (after any spaces and an optional +/-) and stops at the first non-digit.
  • Cousins: atof → double, atol → long, atoll → long long.
  • Forget #include <stdlib.h> and gcc warns: warning: implicit declaration of function 'atoi' [-Wimplicit-function-declaration].

Playing the operating system

The online compiler can't add arguments, so in the video we build argv by hand, exactly as the system would for ./bill 250 4, and pass it to a function that looks like main:

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

int bill(int argc, char *argv[]) {
    printf("argc = %d\n", argc);
    int price = atoi(argv[1]);
    int qty = atoi(argv[2]);
    printf("Total: Rs %d\n", price * qty);
    return 0;
}

int main() {
    char *args[] = {"./bill", "250", "4", NULL};
    return bill(3, args);
}

Output:

argc = 3
Total: Rs 1000

The missing-argument crash

The real program:

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

int main(int argc, char *argv[]) {
    int price = atoi(argv[1]);
    int qty = atoi(argv[2]);
    printf("Total: Rs %d\n", price * qty);
    return 0;
}

In the online compiler (no arguments):

Segmentation fault

In a terminal:

$ ./atoi 250 4
Total: Rs 1000
$ ./atoi 250
Segmentation fault
$ ./atoi
Segmentation fault

Why: with no arguments argc is 1, so argv[1] is the end marker NULL. atoi(NULL) tries to read text at address NULL, and the operating system stops the program, just like the NULL pointer crash in episode 10. With one argument, argv[2] is NULL and the same thing happens. (Reading past argv[argc] is undefined behaviour: anything can happen.) One forgotten word and the whole program crashes with no hint about what it wanted.

Usage messages and exit status

Real-life example: the ATM that tells you what's missing.

At the ATM In C
Card in, no PIN: the machine checks before doing anything if (argc != 3): count the arguments first
"Please enter your PIN": it says exactly what it needs A usage message: Usage: ./bill <price> <quantity>
The card comes back: you know the job wasn't done return 1;: an exit status that means failure
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Usage: %s <price> <quantity>\n", argv[0]);
        return 1;
    }
    int price = atoi(argv[1]);
    int qty = atoi(argv[2]);
    printf("Total: Rs %d\n", price * qty);
    return 0;
}

In the online compiler:

Usage: ./main <price> <quantity>

and the badge says Runtime Error (NZEC): non-zero exit code. It is not a crash here; the program returned 1 on purpose. In a terminal, echo $? prints the exit status of the last program:

$ ./check
Usage: ./check <price> <quantity>
$ echo $?
1
$ ./check 250 4
Total: Rs 1000
$ echo $?
0
  • A usage message is one line that shows how to run the program. Print argv[0] so it shows the real name. By convention <price> means "put a value here" and [tip%] means "optional".
  • The exit status is the number main returns to whoever started the program. 0 = success, anything else (usually 1) = failure. Scripts check it to decide what to do next. <stdlib.h> also has the names EXIT_SUCCESS and EXIT_FAILURE.
  • A crash has its own status: in bash, a Segmentation fault shows as 139 (128 + signal 11).
  • Many programs print the usage message to stderr with fprintf(stderr, ...) so it doesn't mix with real output; printf is fine while learning.

strtol: catching bad numbers

The next problem: atoi never complains.

  • atoi("abc") → 0, with no error. Your program would happily bill zero rupees.
  • atoi("25O") (a capital letter O, not zero) → 25: it stops at the O and says nothing.
  • A real "0" also gives 0, so you can't tell good input from rubbish.

strtol (string to long), also in <stdlib.h>, tells you where it stopped:

char *end;
long n = strtol(text, &end, 10);   // 10 = base ten

After the call, end points to the first character it couldn't read. If *end == '\0' (the end of the string), the whole text was a number.

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

int main() {
    char *tests[] = {"250", "25O", "abc"};
    for (int i = 0; i < 3; i++) {
        char *end;
        long n = strtol(tests[i], &end, 10);
        printf("%-4s atoi: %-4d strtol: ", tests[i],
               atoi(tests[i]));
        if (*end != '\0')
            printf("not a number\n");
        else
            printf("%ld\n", n);
    }
    return 0;
}

Output:

250  atoi: 250  strtol: 250
25O  atoi: 25   strtol: not a number
abc  atoi: 0    strtol: not a number

A check for one argument:

char *end;
long price = strtol(argv[1], &end, 10);
if (*end != '\0') {
    printf("Not a number: %s\n", argv[1]);
    return 1;
}
$ ./strtol 250
Price: Rs 250
$ ./strtol 25O
Not a number: 25O
$ echo $?
1

Extra details: an empty string also leaves end at the start, so a full check is end == text || *end != '\0'; if the number is too big for a long, strtol returns LONG_MAX and sets errno to ERANGE. Use strtod for decimals. Rule of thumb: atoi for quick tests, strtol for input from real users.

Common mistakes (and the real gcc messages)

Mistake What you see Why Fix
argv[1] * argv[2] error: invalid operands to binary * (have 'char *' and 'char *') Arguments are strings atoi(argv[1]) * atoi(argv[2])
atoi(argv[1]) with no argument Segmentation fault argv[1] is NULL if (argc != 3) { usage; return 1; } first
atoi("abc") No error: the value is 0 atoi never reports failure strtol and check *end
if (argc == 2) for two arguments No error: the check is off by one argv[0] is the program's name Two arguments → argc == 3
atoi without #include <stdlib.h> warning: implicit declaration of function 'atoi' atoi was never declared #include <stdlib.h>
./app masala chai meant as one argument argc is 3, not 2 Spaces split arguments ./app "masala chai"
return 0; after an error The script thinks it worked Exit status 0 means success return 1; (or exit(1);)

Mini project: a command-line bill splitter

Four friends finish dinner: ./split <bill> <people> [tip%], with the tip optional.

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

long number(const char *s) {
    char *end;
    long n = strtol(s, &end, 10);
    if (*end != '\0' || n <= 0) {
        printf("Not a positive number: %s\n", s);
        exit(1);
    }
    return n;
}

int main(int argc, char *argv[]) {
    if (argc < 3 || argc > 4) {
        printf("Usage: %s <bill> <people> [tip%%]\n",
               argv[0]);
        return 1;
    }
    long bill = number(argv[1]);
    long people = number(argv[2]);
    long tip = (argc == 4) ? number(argv[3]) : 0;
    long total = bill + bill * tip / 100;
    printf("Total: Rs %ld\n", total);
    printf("Each of %ld pays: Rs %ld\n",
           people, total / people);
    return 0;
}

In the online compiler (no arguments):

Usage: ./main <bill> <people> [tip%]

In a terminal:

$ ./split 1200 4
Total: Rs 1200
Each of 4 pays: Rs 300
$ ./split 1200 4 10
Total: Rs 1320
Each of 4 pays: Rs 330
$ ./split 1200 four
Not a positive number: four
$ ./split 1200 0
Not a positive number: 0

New pieces:

  • exit(1) from <stdlib.h> ends the whole program from inside any function, with that exit status. (return only leaves the current function.)
  • %% in a printf format prints one % sign.
  • The tip is optional, so the program accepts argc of 3 or 4, and uses the conditional operator ?: (episode 3) to pick 0 when it is missing.
  • Checking n <= 0 also protects against dividing by zero people.

Practice

  1. Print all the arguments in reverse order (not the program's name).
  2. ./add 5 7 9: add any number of arguments; reject anything that isn't a number.
  3. ./convert 5 km prints the value in metres; ./convert 2500 m prints kilometres.
  4. Extend the bill splitter: friends who don't drink chai don't pay for it. ./nochai <bill> <people> <chai-cost> <no-chai>.
Solutions

1. Reverse (verified):

#include <stdio.h>

int main(int argc, char *argv[]) {
    for (int i = argc - 1; i >= 1; i--)
        printf("%s\n", argv[i]);
    return 0;
}
$ ./rev chai samosa vada
vada
samosa
chai

2. Add any number of arguments (verified):

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

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: %s <number> [more numbers...]\n", argv[0]);
        return 1;
    }
    long sum = 0;
    for (int i = 1; i < argc; i++) {
        char *end;
        long n = strtol(argv[i], &end, 10);
        if (*end != '\0') {
            printf("Not a number: %s\n", argv[i]);
            return 1;
        }
        sum += n;
    }
    printf("Sum: %ld\n", sum);
    return 0;
}
$ ./add 5 7 9
Sum: 21
$ ./add 5 x
Not a number: x

3. Converter (verified; strcmp from <string.h>, episode 9, compares two strings and gives 0 when they are equal):

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

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Usage: %s <value> <km|m>\n", argv[0]);
        return 1;
    }
    double value = atof(argv[1]);
    if (strcmp(argv[2], "km") == 0)
        printf("%.2f km = %.0f m\n", value, value * 1000);
    else if (strcmp(argv[2], "m") == 0)
        printf("%.0f m = %.3f km\n", value, value / 1000);
    else {
        printf("Unknown unit: %s\n", argv[2]);
        return 1;
    }
    return 0;
}
$ ./convert 5 km
5.00 km = 5000 m
$ ./convert 2500 m
2500 m = 2.500 km
$ ./convert 5 mile
Unknown unit: mile

4. No-chai splitter (verified):

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

long number(const char *s) {
    char *end;
    long n = strtol(s, &end, 10);
    if (*end != '\0' || n < 0) {
        printf("Not a valid number: %s\n", s);
        exit(1);
    }
    return n;
}

int main(int argc, char *argv[]) {
    if (argc != 5) {
        printf("Usage: %s <bill> <people> <chai-cost> <no-chai>\n", argv[0]);
        return 1;
    }
    long bill = number(argv[1]);
    long people = number(argv[2]);
    long chai = number(argv[3]);
    long nochai = number(argv[4]);
    if (people == 0 || nochai > people) {
        printf("Check the number of people\n");
        return 1;
    }
    long drinkers = people - nochai;
    long shared = (bill - chai) / people;
    printf("No-chai friends pay: Rs %ld\n", shared);
    if (drinkers > 0)
        printf("Chai drinkers pay:   Rs %ld\n", shared + chai / drinkers);
    return 0;
}
$ ./nochai 1200 4 120 1
No-chai friends pay: Rs 270
Chai drinkers pay:   Rs 310

Check: 270 + 3 × 310 = 1200.

Quick quiz

What does this print?

// run as:  ./app chai 2 "less sugar"
printf("%d %s", argc, argv[argc - 1]);
  • A. 3 sugar
  • B. 4 less sugar
  • C. 3 less sugar
  • D. 4 sugar
Answer

B: 4 less sugar. argv is ./app, chai, 2, less sugar: four strings, because the program's name counts and the quotes keep less sugar together. The last one, argv[3], is less sugar. (Verified output: 4 less sugar.)

Interview questions

  • What are argc and argv? What are their types?
  • What is in argv[0]? What is argv[argc]?
  • Why is argc at least 1? (On normal systems argv[0] is the program's name; the C standard allows argc to be 0 in rare environments, so very careful code checks argc > 0.)
  • Is char *argv[] the same as char **argv in a parameter list? (Yes: an array parameter becomes a pointer.)
  • Why can't you write argv[1] * argv[2]? How do you convert an argument to a number?
  • What is the difference between atoi and strtol? Why is atoi risky for user input?
  • What happens if you use argv[1] when no argument was given?
  • What is an exit status? What do return 0, return 1, exit(1), EXIT_SUCCESS and EXIT_FAILURE mean?
  • What is the difference between return in main and calling exit() from another function?
  • How do you pass an argument that contains a space?
  • How would you handle options like -v or --help? (Compare with strcmp, or use getopt on POSIX systems.)
  • Can main have a third parameter? (envp, the environment, on many systems; it is not standard C.)

Glossary

Term Meaning Example
Terminal A window where you type commands instead of clicking icons bash on Linux, Terminal on macOS
Shell The program inside the terminal that reads your command and starts programs bash
Command line The line you type to start a program, with its arguments ./bill 250 4
Prompt The symbol the terminal shows when it's waiting for you (you don't type it) $
Argument (command-line argument) An extra word handed to a program when it starts 250 and 4
argc Argument count: how many strings are in argv, including the program's name 3 for ./bill 250 4
argv Argument vector: an array of strings holding the command line, one word each argv[1] is "250"
argv[0] The name the program was started with "./bill"
argv[argc] Always NULL: the end marker after the last argument argv[3] for ./bill 250 4
String array An array whose items are strings (char *) char *tests[] = {"250", "abc"};
NULL A pointer to nothing; reading through it crashes argv[1] when there are no arguments
Segmentation fault The operating system stopping a program that touched memory it may not use atoi(NULL)
<stdlib.h> The standard library header with atoi, strtol, exit and more #include <stdlib.h>
atoi ASCII to integer: turns text into an int; returns 0 for rubbish, with no error atoi("250") → 250
ASCII The code that stores each character as a number '2' is 50
strtol String to long: turns text into a long and tells you where it stopped strtol(s, &end, 10)
End pointer The char * that strtol sets to the first character it couldn't read *end == '\0' → all digits
Base The number system for strtol; 10 is the normal decimal system 10
Usage message One line that shows how to run a program Usage: ./bill <price> <quantity>
Exit status (exit code) The number a program gives back when it ends: 0 = success, non-zero = failure return 1;
NZEC Non-zero exit code: how online judges and the SyntaxPilot compiler label a program that returned non-zero Runtime Error (NZEC)
exit() Ends the whole program from any function, with an exit status exit(1);
echo $? A shell command that prints the last program's exit status 1
Optional argument An argument the user may leave out, shown in [ ] in a usage message [tip%]

Summary

  • A program that asks with scanf can't run on its own; nobody is there to answer, and the variables keep garbage.
  • Give the input when the program starts: the command line, like ./bill 250 4. Words separated by spaces are arguments; quotes keep words together.
  • main receives them as int main(int argc, char *argv[]). argc counts the strings including the program's name; argv[0] is the name and argv[argc] is NULL.
  • Arguments are strings: convert them with atoi, or better, strtol with an end pointer, which catches "abc" and "25O".
  • Always check argc first. Using a missing argument reads NULL and gives a Segmentation fault.
  • When the input is wrong, print a usage message and return 1 (or exit(1) from another function): the exit status tells scripts the job failed. 0 means success.

Next episode: Multi-file programs and header files: split one big main.c into several files, write your own .h, and compile them together, with include guards used for real.