Presented By:
Priyanshu & Rohit
Command
Line
Arguments
Command
Line Arguments
Command-line arguments are given after the name of the program in
command-line shell of Operating Systems. To pass command line
arguments, we typically define main() with two arguments:
First argument is the number of command line arguments and second
is list of command-line arguments.
❖ int main(int argc, char *argv[]) { /* ... */ }
or
❖ int main(int argc, char **argv) { /* ... */ }
Argc
(ARGument
Count) Argv
(ARGument
Vector)
Argc
(ARGument Count)
❖It is int and stores number of command-line arguments passed by
the user including the name of the program.
❖So, if we pass a value to a program, value of Argc would be 2 (one for
argument and one for program name)
❖The value of Argc should be non negative.
Argv
(ARGument Vector)
❖ It is array of character pointers listing all the arguments.
❖ If argc is greater than zero, the array elements from argv[0] to
argv[argc-1] will contain pointers to strings.
❖ Argv[0] is the name of the program, After that till argv[argc-1] every
element is command-line arguments.
A rguments
Examples :
// Name of program demo.cpp
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
cout << "You have entered " << argc
<< " arguments:" << "\n";
for (int i = 0; i < argc; ++i)
cout << argv[i] << "\n";
return 0;
}
Arguments
Input:
$ g++ demo.cpp-o main
$ ./main hello hi
Output:
You have entered 3
arguments:
▪ ./main
▪ hello
▪ hi
Properties of Command Line A rguments
a) They are passed to main() function.
b) They are parameters/arguments supplied to the program when it is
invoked.
c) argv[argc] is a NULL pointer.
d) argv[0] holds the name of the program.
e) argv[1] points to the first command line argument and argv[n] points last
argument.
Spacing in Command Line A rguments
You pass all the command line arguments separated by a
space, but if argument itself has a space, then you can
pass such arguments by putting them inside
(Double quotes or Single quotes) .
Double Single
Quotes Quotes
Double Single
Quotes Quotes
Double Quotes
When the above code is
compiled and executed with
Single
a single argument separated
by space but inside double
Quotes
quotes.
Single Quotes
Double When the above code is
compiled and executed with
Quotes a single argument separated
by space but inside single
quotes.
Quiz Time
Q. What is the signature of math in function using
command line arguments?
a) int main(int argc, char const *argv[]);
b) int main(int argc, char const **argv);
c) int main(int argc, char **argv);
d) all of the mentioned
Answer: D
Quiz Time
Q. To use command line arguments in C++, how many
parameters are passed to the main function?
a) 1
b) 2
c) 3
d) 4
Answer: B
Quiz Time
Q. What are command line arguments?
a) Arguments passed to main() function
b) Arguments passed to any function
c) Arguments passed to class functions
d) Arguments passed to structure functions
Answer: A
Thank You
Arigatōgozaimashita