Skip to content
StudyFame

Command Line Arguments in C

So far, your programs got input with scanf after they started. But many programs take input when they start: you type gcc main.c -o app, and gcc receives "main.c", "-o" and "app". These are called command line arguments.

In this lesson you will learn how main receives them through argc and argv, how to turn them into numbers, how to check that the user gave the right number of values, and how to write small tools like a sum program and a calculator.

What You Will Learn

  • What command line arguments are.
  • The meaning of argc and argv.
  • Why argv[0] is the program name.
  • How to convert arguments to numbers with atoi, atof and strtol.
  • How to check the argument count and print a usage message.
  • How to pass arguments in an IDE as well as in the terminal.

Command Line Arguments in C Explained

Exam definition: Command line arguments are values passed to a program when it is run from the command line. They are received by main through two parameters: int argc (argument count), the number of arguments including the program name, and char *argv[] (argument vector), an array of strings where argv[0] is the program name, argv[1] to argv[argc-1] are the arguments, and argv[argc] is NULL.

Memory trick: When you board a bus, the conductor writes a passenger list. argc = how many people are on the list (count). argv = the list of names (vector). The driver's name is always first (argv[0] = the program itself), and every value is written as text, even numbers.

Syntax of main with Arguments

int main(int argc, char *argv[])   /* most common form           */
int main(int argc, char **argv)    /* exactly the same meaning   */

/* Running:   ./prog  apple  42  "New Delhi"
   argc    =  4
   argv[0] = "./prog"
   argv[1] = "apple"
   argv[2] = "42"          (a string, not the number 42)
   argv[3] = "New Delhi"   (quotes keep words together)
   argv[4] = NULL                                          */

The names argc and argv are only a convention, but every C programmer uses them.

Example 1: Printing All Arguments

Save the program as args.c, compile it and run it with three arguments:

gcc args.c -o args
./args Delhi 25 hello
#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;

    printf("argc = %d\n", argc);
    for (i = 0; i < argc; i++)
        printf("argv[%d] = %s\n", i, argv[i]);
    return 0;
}

Output

argc = 4
argv[0] = ./args
argv[1] = Delhi
argv[2] = 25
argv[3] = hello

Code Explanation

  1. int main(int argc, char *argv[]): the operating system calls main and fills these two parameters for us.
  2. argc is 4: the program name plus three arguments.
  3. argv[0] is the program name exactly as typed (./args). On Windows it may be the full path, like C:\code\args.exe.
  4. argv[1], argv[2], argv[3] are the arguments. Notice "25" is printed with %s: it is a string.
  5. The loop runs from 0 to argc - 1. It must never read beyond argv[argc], which is NULL.

How Command Line Arguments Work

The shell splits what you type at spaces, stores each word as a string and gives main an array of pointers to them:

You type:  ./args Delhi 25 hello

argv ──► [0] ──► "./args"
         [1] ──► "Delhi"
         [2] ──► "25"
         [3] ──► "hello"
         [4] ──► NULL
argc = 4
  • To pass a value containing spaces, use quotes: ./args "New Delhi" gives one argument.
  • Numbers arrive as text. Convert them: atoi(argv[1]) for int, atof(argv[1]) for double, or strtol when you need error checking.
  • In Code::Blocks use Project → Set programs' arguments; in VS Code, add them to the run command in the terminal.

Example 2: Sum and Average of Numbers from the Command Line

./sum 10 20 30.5
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int i;
    double total = 0;

    if (argc < 2)
    {
        printf("Usage: %s num1 num2 ...\n", argv[0]);
        return 1;
    }

    for (i = 1; i < argc; i++)
        total += atof(argv[i]);

    printf("Numbers given: %d\n", argc - 1);
    printf("Sum     = %.2f\n", total);
    printf("Average = %.2f\n", total / (argc - 1));
    return 0;
}

Output

Numbers given: 3
Sum     = 60.50
Average = 20.17
  • The loop starts at 1, because argv[0] is the program name, not a number.
  • atof converts "30.5" into the double 30.5.
  • If the user runs ./sum with no numbers, the program prints a usage message and returns 1 (a non-zero exit code means "failed"). Always check argc before using argv[1].

Important Points to Remember

  • argc = number of arguments including the program name, so it is always at least 1.
  • argv[0] = program name; real arguments start at argv[1].
  • Every argument is a string; convert numbers with atoi, atof or strtol.
  • argv[argc] is always NULL.
  • Check argc first and print a usage message if values are missing.
  • Arguments are separated by spaces; use quotes for values with spaces.

Common Mistakes Beginners Make

MistakeWhat happensFix
Using argv[1] without checking argcCrash when no argument is givenif (argc < 2) { usage; return 1; }
int n = argv[1];Stores a pointer, not the numberint n = atoi(argv[1]);
Loop starting at 0 when adding numbersTries to convert the program nameStart the loop at 1
if (argv[1] == "add")Compares addresses, always falsestrcmp(argv[1], "add") == 0
Thinking argc counts only the argumentsOff-by-one errorsRemember argc includes argv[0]

Command Line Arguments Practice Questions

  1. What are argc and argv? What are their types?
  2. What is the value of argc for ./app one two?
  3. What does argv[0] contain?
  4. Why must arguments be converted before arithmetic?
  5. How do you pass "Hello World" as a single argument?
Show answers
  1. argc (int) is the number of arguments including the program name; argv (char *[]) is an array of strings holding them.
  2. 3.
  3. The program name (as typed, or the full path on some systems).
  4. Because every argument is a string; "25" is text, so it must be converted with atoi/atof/strtol.
  5. Put it in quotes: ./app "Hello World".

Coding Exercise

Write calc.c that is run as ./calc 12 x 5 and prints the result. Support +, -, x (multiply, because * means "all files" to the shell) and /. Print a usage message if there aren't exactly 3 arguments.

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

int main(int argc, char *argv[])
{
    double a, b, result;

    if (argc != 4)
    {
        printf("Usage: %s number op number   (op: + - x /)\n", argv[0]);
        return 1;
    }
    a = atof(argv[1]);
    b = atof(argv[3]);

    if (strcmp(argv[2], "+") == 0)      result = a + b;
    else if (strcmp(argv[2], "-") == 0) result = a - b;
    else if (strcmp(argv[2], "x") == 0) result = a * b;
    else if (strcmp(argv[2], "/") == 0)
    {
        if (b == 0) { printf("Error: division by zero\n"); return 1; }
        result = a / b;
    }
    else
    {
        printf("Unknown operator: %s\n", argv[2]);
        return 1;
    }

    printf("%s %s %s = %g\n", argv[1], argv[2], argv[3], result);
    return 0;
}
12 x 5 = 60

Quick Quiz: Command Line Arguments (MCQ)

  1. For ./prog a b c, argc is:

    A) 3   B) 4   C) 2   D) 5

  2. The type of argv is:

    A) int[]   B) char   C) char *[]   D) float *

  3. argv[0] holds:

    A) The first argument   B) The program name   C) NULL   D) argc

  4. Which function converts "45" to the integer 45?

    A) atoi   B) itoa   C) strlen   D) printf

  5. argv[argc] is:

    A) The last argument   B) Garbage   C) NULL   D) The program name

Show answers
  1. B: 4.
  2. C: char *[].
  3. B: the program name.
  4. A: atoi.
  5. C: NULL.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

Signatureint main(int argc, char *argv[])
argcArgument count, includes the program name
argvArgument vector: array of strings
argv[0]Program name
argv[argc]NULL
NumbersArrive as strings: use atoi / atof / strtol
Spaces in a valueWrap it in quotes

Frequently asked questions

What are command line arguments in C?
Values given to a program when it starts, received by main as argc (count) and argv (array of strings).
Why is argc at least 1?
Because argv[0] always holds the program name.
How do you use a numeric command line argument?
Convert the string with atoi(), atof() or strtol() before doing arithmetic.

Remember

  • argc = count, argv = list; the driver (program name) comes first.
  • Check argc before touching argv[1].

Next Topic

Next lesson: Variadic Functions in C. You will write functions like printf that accept any number of arguments using stdarg.h.