
Command Line Arguments in C
Command-line arguments in C are parameters provided to a program when it is executed from a command line interface (CLI). They allow users to pass information to the program at runtime, making the program more flexible and dynamic. These arguments are passed to the main function, which can be defined to accept them.
In C, the main function can be defined to accept command-line arguments as follows :
Explanation :
- argc (argument count) : This is an integer that indicates the number of command-line arguments passed to the program, including the program name.
- argv (argument vector) : This is an array of strings (character pointers) representing the command-line arguments. argv[0] is the name of the program, and argv[1] to argv[argc-1] are the actual command-line arguments.
1. Save the above program as example.c.
2. Compile the program using a C compiler, e.g., gcc:
gcc -o example example.c
3. Run the program with command-line arguments :
./example arg1 arg2 arg3
4. Output :
Number of arguments: 4
Argument 0: ./example
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3
Sum : 15
Average: 30.00
Command-line arguments significantly enhance the usability, flexibility, and functionality of C programs by allowing dynamic input, enabling automation, simplifying testing, promoting standardization, and improving resource management. They make programs more adaptable to different use cases and environments, which is essential for developing robust and efficient software.