Command Line Arguments in
C–
So far, we have seen that no arguments were passed in the main
function. But the C programming language gives the programmer
the provision to add parameters or arguments inside the main
function to reduce the length of the code. These arguments are
called Command Line Arguments in C.
In this tutorial, we will discuss:
Components of Command Line Arguments
C program to understand command line arguments
What are Command Line
Arguments in C?
Command line arguments are simply arguments that are specified
after the name of the program in the system’s command line, and
these argument values are passed on to your program during
program execution.
Components of Command Line
Arguments
There are 2 components of Command Line Argument in C:
1. argc: It refers to “argument count”. It is the first
parameter that we use to store the number of command
line arguments. It is important to note that the value of
argc should be greater than or equal to 0.
2. agrv: It refers to “argument vector”. It is basically an
array of character pointer which we use to list all the
command line arguments.
In order to implement command line arguments, generally, 2
parameters are passed into the main function:
1. Number of command line arguments
2. The list of command line arguments
The basic syntax is:
int main( int argc, char *argv[] )
{
// BODY OF THE MAIN FUNCTION
}
or it can also be written as
int main( int argc, char **argv[] )
{
// BODY OF THE MAIN FUNCTION
}
Still Confused about Syntax! Learn the Basic Syntax Rules in
C Programming
Example of C Command Line
Arguments
Here is a code in C that illustrates the use of command line
arguments.
cl.c
// The program name is
#include<stdio.h>
int main(int argc, char* argv[])
{
printf("Welcome to DataFlair tutorials!\n\n");
int i;
printf("The number of arguments are: %d\
n",argc);
printf("The arguments are:");
for( i = 0; i < argc; i++)
{
printf("%s\n", argv[i]);
}
int sum=atoi(argv[1])+atoi(argv[2])
+atoi(argv[3]);
return 0;
}
Code on Screen-
Output-
C:> ./a.out 10 20 30 hello hai how are you