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
argcandargv - How quoting affects arguments
- Converting arguments to numbers with
strtod - Printing usage messages to
stderr - Returning
EXIT_SUCCESSandEXIT_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 atargv[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]isNULL, 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. strtodconverts text to adoubleand setsendto the first character it could not use. If*endis not the end of the string, the argument was not a valid number. (See String to Number Conversion.)- Error messages go to
stderrwithfprintf, 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.xis used for multiplication because the shell would expand an unquoted*into a list of file names.
Common Mistakes
- Reading
argv[1]without checkingargc, which crashes when no argument is given. - Using
atoi, which silently returns 0 for invalid input. - Comparing strings with
==; usestrcmp(argv[1], "-h") == 0. - 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
argccounts the arguments;argvholds them as strings, with the program name inargv[0].- Always check
argcbefore readingargv. - Convert with
strtol/strtodand validate the result. - Report errors on
stderrand returnEXIT_FAILURE.
