Command Line Arguments in C
Introduction
Command line arguments in C are arguments that are passed into your program at the time of execution. These arguments are used to control the program from the outside instead of hard coding those values inside the code. The command line arguments are handled using the main function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program.
Using Command Line Arguments in C
The command line arguments are passed through the main function. The prototype of the main function in this case looks like this:
int main(int argc, char *argv[])
Here, argc counts the number of command line arguments. The name of the program itself is considered an argument, and its name is stored in argv[0]. So, the count of argc starts from 1.
The argv is a pointer array which points to each command line argument that is passed to your program.
Example
Let's look at a simple example of command line arguments in C.
#include<stdio.h>
int main(int argc, char *argv[]) {
int counter;
printf("\nProgram Name Is: %s",argv[0]);
if(argc==1)
printf("\nNo Extra Command Line Argument Passed Other Than Program Name");
if(argc>=2) {
printf("\nNumber Of Arguments Passed: %d",argc);
printf("\n----Following Are The Command Line Arguments Passed----");
for(counter=0;counter<argc;counter++)
printf("\nargv[%d]: %s",counter,argv[counter]);
}
return 0;
}
In the above example, we first print the name of the program itself, which is stored in argv[0]. Then, we check if any extra command line arguments are passed or not. If passed, then we print the number of these arguments and also the arguments themselves.
Conclusion
Command line arguments are an important concept in C programming, especially when you want to control your program from the outside. The argc and argv parameters to the main function hold the key to command line arguments. With these, you can pass additional information to your program at runtime without having to modify your program.