Command Line Arguments allow users to pass inputs to a program at the time of running it, rather than giving input during execution.
✅ They are essential for building flexible and dynamic programs, commonly used in real-world tools, automation scripts, compilers, etc.
🧠 Why Do We Need Command Line Arguments?
Imagine you're creating a file-copy program like:
$ ./filecopy source.txt destination.txtHere:
./filecopyis the program namesource.txtanddestination.txtare command line arguments
They allow your program to:
Accept input from the user at runtime
Automate actions (used in shell scripts, pipelines)
Reduce manual input prompts
🔧 Basic Syntax of main() with Command Line Arguments
int main(int argc, char *argv[])OR
int main(int argc, char **argv)Term | Meaning |
|---|---|
| Argument Count – Number of arguments passed to the program (including program name) |
| Argument Vector – Array of strings (character pointers), each containing one argument |
🔍 How It Works
./program Hello WorldNow:
argc= 3argv[0]="./program"argv[1]="Hello"argv[2]="World"
📌 Always remember:
argv[0]is always the program nameThe rest are actual arguments passed by the user
🧪 Simple Example
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Number of arguments: %d\\n", argc);
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\\n", i, argv[i]);
}
return 0;
}If you run:
./myProgram Apple Banana
Number of arguments: 3
Argument 0: ./myProgram
Argument 1: Apple
Argument 2: Banana🎯 Real Use Case: Sum Two Numbers via CLI
#include <stdio.h>
#include <stdlib.h> // For atoi()
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s num1 num2\\n", argv[0]);
return 1;
}
int a = atoi(argv[1]); // Convert string to int
int b = atoi(argv[2]);
printf("Sum: %d\\n", a + b);
return 0;
}./sum 10 20
Sum: 30🔐 Important Functions for Command Line Processing
Function | Purpose |
|---|---|
| Convert string to |
| Convert string to |
| Compare two strings |
| Get length of string |
🧩 Things to Watch Out For
❗ Always check
argcbefore accessingargv[i]to avoid segmentation fault( your program tries to access memory that it doesn't have permission to use**)**⚠️ Use
atoi()carefully — it doesn't report conversion errors🧹 Consider using
strtol()for safer conversion thanatoi()
⚠️ Use Case of strtol(): Converting User Input to Integer
🎯 Scenario:
Imagine you're writing a program that asks the user to enter their age, and you need to convert the input string into an integer. You want to ensure that:
The input is a valid number
There is no garbage input after the number
You can detect errors gracefully
❌ Problem with atoi():
char input[] = "25abc";
int age = atoi(input); // Converts only "25", ignores "abc"
printf("Age: %d\\n", age); // Output: 25 (but input was invalid!)👉 atoi() gives no way to detect if conversion was partial or invalid. It simply stops at the first non-digit and continues silently.
✅ Better with strtol():
#include <stdio.h>
#include <stdlib.h>
int main() {
char input[] = "25abc";
char *endptr;
long age = strtol(input, &endptr, 10);
if (*endptr != '\\0') {
printf("❌ Invalid input. Non-digit characters found: %s\\n", endptr);
} else {
printf("✅ Age: %ld\\n", age);
}
return 0;
}❌ Invalid input. Non-digit characters found: abc💡 Why strtol() is Better Than atoi():
Feature |
|
|
|---|---|---|
Error detection | ❌ None | ✅ Yes ( |
Overflow/underflow check | ❌ No | ✅ Can be handled |
Partial conversion | ✅ Silently | ❌ Detected |
Input validation | ❌ Lacks | ✅ Robust |
🧠 Memory Behind the Scenes
argvis an array of pointersThese point to memory locations of the strings passed via terminal
All command line arguments are passed from OS to your
main()function before execution begins
🛠️ Advanced Use Case: Looping Over Arguments
int i;
for (i = 1; i < argc; i++) {
printf("Argument %d is %s\\n", i, argv[i]);
}This way, you can:
Read filenames
Handle options like
v,-help,-output=Build real CLI tools