Command-Line Arguments in C Programming (Complete Guide with Examples)
This tutorial explains command-line arguments in C, which allow users to pass information to a program when it is executed. It covers argc, argv, and practical examples to make programs flexible and interactive.
1. What are Command-Line Arguments
- Command-line arguments allow passing inputs to a C program while running it from the terminal.
- Useful when you want programs to accept parameters dynamically instead of using
scanf(). - Two parameters are used in
main()to handle command-line arguments:
int main(int argc, char *argv[])
| ParameterDescription | |
argc | Argument count – number of arguments passed including program name |
argv | Argument vector – array of strings containing the arguments |
2. Example: Display Command-Line Arguments
#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;
}
Example Run:
$ ./program Muni 25 Mumbai
Number of arguments: 4
Argument 0: ./program
Argument 1: Muni
Argument 2: 25
Argument 3: Mumbai
Explanation:
argv[0]always contains the program name- Subsequent elements (
argv[1]onward) contain user-provided arguments
3. Example: Sum of Two Numbers Using Command-Line Arguments
#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 num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);
int sum = num1 + num2;
printf("Sum = %d\n", sum);
return 0;
}
Example Run:
$ ./program 10 20
Sum = 30
Explanation:
atoi()converts string to integer- Command-line arguments allow program to be flexible and reusable
4. Key Points to Remember
argccounts all arguments, including program nameargvis an array of *strings (char )- Use
atoi()oratof()to convert arguments to numbers - Useful for scripts, automation, and dynamic input programs