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:
| 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
Example Run:
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
Example Run:
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