The arguments passed from the command line are called command-line arguments. Command-line arguments are passed to the main() method.
It allows you to pass the values in a program when they are executed. This is useful when the developer wants to control the program from the outside.
Since the values passed to the main()
function, there are changes that need to be made in main()
function. See the syntax below.
1 | int main(int argc, char *argv[]) |
Let us see each of the argument passed:
argv
– It is the total number of arguments in the command line including the program name. It counts the file name as the first argument.argv[]
– It contains all the arguments, the first one being the file name itself.
Example: C Program for Command Line Argument
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <stdio.h> void main(int argc, char *argv[] ) { printf("Program name itself is: %s\n", argv[0]); if(argc < 2) { printf("No argument passed through command line.\n"); } else { printf("First argument is: %s\n", argv[1]); } } |
Note that argv[0]
holds the name of the program itself and argv[1]
points to the first command-line argument and argv[n]
gives the last argument.
Output:
Run the above program in windows by passing an argument.
cprogram.exe simple2code
It will print the following result:
1 2 | Program name itself is: cprogram First argument is: simple2code |
Now if you pass multiple arguments (like: cprogram.exe simple2code is website
), it will still display the same result as above.
But is you pass the argument in double quote, the program will treat that as one single value.
cprogram.exe “simple2code is a Website”
It will display the following result:
1 2 | Program name itself is: cprogram First argument is: simple2code is a Website |
If no argument is supplied, argc will be 1.