C allows passing values from thecommand line at execution time in the program. In this tutorial, you will learn about using command-line arguments in C.
Themain() function is the most significant function of C and C++ languages. Thismain() is typically defined as having a return type of integer and having no parameters; something like this:
Example:
int main(){ // body of the main() function}C allows programmers to putcommand-line arguments within the program, allowing users to add values at the very start of program execution.
What are Command line arguments?
Command line arguments are the arguments specified after the program name in the operating system's command line. These argument values are passed to your program during execution from your operating system. To use this concept in your program, you have to understand the complete declaration of how themain() function works with the command-line argument to fetch values that earlier took no arguments with it (main() without any argument).
So you can program themain() in such a way that it can essentially accept two arguments where the first argument denotes the number of command line arguments and the second denotes the complete list of every command line argument. It is how you can code your command line argument within the parenthesis ofmain():
Example:
int main ( int argc, char *argv [ ] )In the above statement, the command line arguments have been handled via themain() function, and you have set the arguments where
- argc (ARGument Count) denotes the number of arguments to be passed and
- argv [ ] (ARGument Vector) denotes a pointer array pointing to every argument that has been passed to your program.
You must make sure that in your command line argument,argv[0] stores the name of your program, similarly,argv[1] gets the pointer to the 1st command line argument that the user has supplied, and*argv[n] denotes the last argument of the list.
Program for Command Line Argument
Example:
#include <stdio.h> int main( int argc, char *argv [] ){ printf(" \n Name of my Program %s \t", argv[0]); if( argc == 2 ) { printf("\n Value given by user is: %s \t", argv[1]); } else if( argc > 2 ) { printf("\n Many values given by users.\n"); } else { printf(" \n Single value expected.\n"); }}Output:
