![]() |
VOOZH | about |
The most important function of C is the main() function. It is mostly defined with a return type of int and without parameters.
int main() {
...
}
We can also give command-line arguments in C. Command-line arguments are the values given after the name of the program in the command-line shell of Operating Systems. Command-line arguments are handled by the main() function of a C program.
To pass command-line arguments, we typically define main() with two arguments: the first argument is the number of command-line arguments and the second is a list of command-line arguments.
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
Here,
For better understanding run this code on your Linux machine.
The below example illustrates the printing of command line arguments.
Output
You have entered 4 arguments:
./main
geeks
for
geeks
for Terminal Input
$ g++ mainreturn.cpp -o main $ ./main geeks for geeksNote: Other platform-dependent formats are also allowed by the C standards; for example, Unix (though not POSIX.1) and Microsoft Visual C++ have a third argument giving the program’s environment, otherwise accessible through getenv in stdlib.h. Refer C program to print environment variables for details.
Note: You pass all the command line arguments separated by a space, but if the argument itself has a space, then you can pass such arguments by putting them inside double quotes "" or single quotes ''.
The below program demonstrates the working of command line arguments.
1. Without argument: When the above code is compiled and executed without passing any argument, it produces the following output.
Terminal Input
$ ./a.outOutput
Program Name Is: ./a.out
No Extra Command Line Argument Passed Other Than Program Name
2. Three arguments: When the above code is compiled and executed with three arguments, it produces the following output.
Terminal Input
$ ./a.out First Second ThirdOutput
Program Name Is: ./a.out
Number Of Arguments Passed: 4
----Following Are The Command Line Arguments Passed----
argv[0]: ./a.out
argv[1]: First
argv[2]: Second
argv[3]: Third
3. Single Argument: When the above code is compiled and executed with a single argument separated by space but inside double quotes, it produces the following output.
Terminal Input
$ ./a.out "First Second Third"Output
Program Name Is: ./a.out
Number Of Arguments Passed: 2
----Following Are The Command Line Arguments Passed----
argv[0]: ./a.out
argv[1]: First Second Third
4. A single argument in quotes separated by space: When the above code is compiled and executed with a single argument separated by space but inside single quotes, it produces the following output.
Terminal Input
$ ./a.out 'First Second Third'Output
Program Name Is: ./a.out
Number Of Arguments Passed: 2
----Following Are The Command Line Arguments Passed----
argv[0]: ./a.out
argv[1]: First Second Third