13. Command-Line ArgumentsIntermediate9 min read
Command-Line Arguments: argc & argv in C
Build robust command-line utilities. Learn argument count (argc), argument vector (argv), converting inputs (atoi, strtol), and flag parsing.
Key Takeaways & Core Concepts
int main(int argc, char *argv[])receives arguments passed from the shell.argcis the total count of arguments (always >= 1).argv[0]contains the name or invocation path of the program itself.argv[argc]is guaranteed by the C standard to be aNULLpointer.- Use
strtol()rather thanatoi()for safe string-to-number conversion with error detection.
How Shell Arguments are Passed to main()
When a user runs ./my_tool -v --input data.txt, the operating system shell splits the string by whitespace and passes an array of null-terminated strings to main.
C Code Example
1int main(int argc, char *argv[])
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
1 lines
argc= 4argv[0]="./my_tool"argv[1]="-v"argv[2]="--input"argv[3]="data.txt"argv[4]=NULL
Complete CLI Option Parser in C
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5int main(int argc, char *argv[]) {
6 printf("Program Name: %s\n", argv[0]);
7 printf("Total Arguments: %d\n\n", argc);
8
9 if (argc < 2) {
10 printf("Usage: %s <num1> <num2> [-v]\n", argv[0]);
11 return 1;
12 }
13
14 int sum = 0;
15 int isVerbose = 0;
16
17 for (int i = 1; i < argc; i++) {
18 if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) {
19 isVerbose = 1;
20 } else {
21 int val = atoi(argv[i]);
22 sum += val;
23 if (isVerbose) printf("[Verbose] Adding %d to running sum\n", val);
24 }
25 }
26
27 printf("Calculated Total Sum: %d\n", sum);
28 return 0;
29}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
29 lines
Note: Notice how argv flags (-v) and numeric arguments are parsed sequentially in the loop.
Practice & AssessmentC Programming Complete Course
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 1 correct(0 attempted)
1
What does argv[0] always contain in a standard C program?
Beginner