Skip to content

Module 8 · Files, the Preprocessor and Program Organisation — topic 4 of 4

Command-Line Arguments

main can receive the words typed after the program name. Learn argc and argv, converting arguments to numbers safely with strtol, and writing proper usage messages and exit codes.

Beginner 12 min read·Lesson 34 of 37 in C Programming

Learning objectives

  • Read argc and argv in main
  • Convert argument strings to numbers with error checking
  • Return meaningful exit codes and print usage messages

Definition

In a hosted environment, main may be declared as int main(int argc, char *argv[]), where argc is the number of arguments and argv is an array of argc strings — argv[0] is the program name — terminated by argv[argc] == NULL.

Introduction

Command-line tools such as gcc hello.c -o hello take their input from arguments rather than interactive prompts. That makes them scriptable: they can be run from other programs, build systems and batch files.

Your C programs can work the same way. The operating system passes the words of the command to main as an array of strings.

Why it matters

Projects like a mini shell, file encryption tool and file compression utility take file names and options from the command line.

Exit codes (return 0 for success, non-zero for failure) let scripts and build tools react to your program's result.

Detailed explanation

For the command ./calc 12 + 30, argc is 4 and argv is {"./calc", "12", "+", "30", NULL}.

Every argument is a string. Convert numbers with strtol (integers) or strtod (floating point). Unlike atoi, strtol reports errors: check that it consumed the whole string and that errno is not ERANGE.

Check argc before reading argv[i]; reading past argc is undefined behaviour (argv[argc] itself is NULL).

Print a usage message to stderr (fprintf(stderr, ...)) when arguments are wrong, and return a non-zero status such as EXIT_FAILURE from <stdlib.h>.

Arguments containing spaces must be quoted by the user: ./greet "Asha Rao" arrives as one argument.

Syntax

C
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "usage: %s NUMBER\n", argv[0]);
return EXIT_FAILURE;
}
char *end;
long n = strtol(argv[1], &end, 10);
if (*end != '\0') { /* not a valid number */ }
return EXIT_SUCCESS;
}
  • char **argv is equivalent to char *argv[] in a parameter.
  • EXIT_SUCCESS (0) and EXIT_FAILURE come from <stdlib.h>.
  • Run with arguments: ./prog 5 10.

Code examples

Listing the arguments

C
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("argc = %d\n", argc);
for (int i = 1; i < argc; i++)
printf("argv[%d] = %s\n", i, argv[i]);
if (argc == 1)
printf("no arguments given\n");
return 0;
}
Output
argc = 1
no arguments given

Run as ./args red green to see argc = 3 and both words.

Running with arguments

Terminal
./args red "light green" 42
# argc = 4
# argv[1] = red
# argv[2] = light green
# argv[3] = 42

More examples

A safe argument-driven calculator

C
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
static int parse_long(const char *s, long *out) {
char *end;
errno = 0;
long v = strtol(s, &end, 10);
if (end == s || *end != '\0' || errno == ERANGE) return 0;
*out = v;
return 1;
}
static int run(int argc, char *argv[]) {
if (argc != 4) {
printf("usage: %s A OP B (OP is + - x /)\n", argv[0]);
return EXIT_FAILURE;
}
long a, b;
if (!parse_long(argv[1], &a) || !parse_long(argv[3], &b)) {
printf("error: operands must be whole numbers\n");
return EXIT_FAILURE;
}
switch (argv[2][0]) {
case '+': printf("%ld\n", a + b); break;
case '-': printf("%ld\n", a - b); break;
case 'x': printf("%ld\n", a * b); break;
case '/':
if (b == 0) { printf("error: division by zero\n"); return EXIT_FAILURE; }
printf("%ld\n", a / b); break;
default: printf("error: unknown operator %s\n", argv[2]); return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
int main(void) {
/* Simulate several command lines so the example runs on its own. */
char *ok[] = {"calc", "12", "x", "30", NULL};
char *bad[] = {"calc", "12", "+", "3O", NULL};
char *missing[] = {"calc", "5", NULL};
printf("status %d\n", run(4, ok));
printf("status %d\n", run(4, bad));
printf("status %d\n", run(2, missing));
return 0;
}
Output
360
status 0
error: operands must be whole numbers
status 1
usage: calc A OP B   (OP is + - x /)
status 1

Step-by-step explanation

  • run takes argc/argv exactly like main, so it can be tested with simulated command lines; a real program would call return run(argc, argv); from main.
  • parse_long rejects empty input (end == s), trailing junk such as the letter O in "3O" (*end != '\0') and out-of-range values (ERANGE).
  • argv[2][0] is the first character of the operator argument. x is used for multiplication because the shell expands * into file names.
  • Each error path prints a message and returns EXIT_FAILURE (1), which scripts can detect.

Expected output

Running “A safe argument-driven calculator” prints exactly:

TextOutput
360
status 0
error: operands must be whole numbers
status 1
usage: calc A OP B (OP is + - x /)
status 1

Practical applications

  • Compilers, git, ls and ping are controlled entirely through arguments.
  • Build scripts check exit codes to stop when a step fails.
  • Utilities such as grep pattern file read options and file names from argv.

Best practices

  • Validate the number and format of arguments first and print a usage line.
  • Use strtol/strtod for numeric arguments.
  • Return EXIT_SUCCESS/EXIT_FAILURE so callers can check the result.

Common mistakes

Reading argv without checking argc

Avoid

#include <stdio.h>
int main(int argc, char *argv[]) {
printf("%s\n", argv[1]);
}

Prefer

#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc > 1) printf("%s\n", argv[1]);
}

With no arguments, argv[1] is NULL; printing it is undefined behaviour.

Using atoi without validation

Avoid

int n = atoi(argv[1]); /* "abc" gives 0 silently */

Prefer

char *end;
long n = strtol(argv[1], &end, 10);
if (*end != '\0') { /* report the error */ }

atoi cannot report errors; strtol tells you where parsing stopped.

Important notes

  • The strings in argv belong to the program and may be modified, but it is clearer to copy them before changing them.
  • Option-parsing libraries such as POSIX getopt handle flags like -v and --output file for larger tools.

Key takeaways

  • argc counts arguments; argv[0] is the program name.
  • All arguments are strings — convert with strtol and check errors.
  • Print usage and return a non-zero status on bad input.

Try it yourself

  1. 1
    Write ./sum 4 8 15 16 that prints the total of all numeric arguments and rejects invalid ones.
  2. 2
    Write a tool ./upper file.txt that prints a file in capital letters, with a usage message when the file name is missing.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

3 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerFor the command `./app one two`, what is the value of argc?
  • ModerateWhy is `strtol` preferred over `atoi` for parsing a numeric argument?
  • AdvancedWhat is guaranteed about `argv[argc]`?
Practise this topic