Command line arguments In C Language
Just like other functions, main() can also receive the arguments and return a value.
It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments.

We can execute a program (executable file) from operating system’s command prompt by just typing the program name as shown below

C:\tc\bin\> sum.exe //here “.exe” is optional

(Suppose if our program is “sum.c” then its compiled version will be “sum.exe”)

When a program is run, the operating system loads exe file into memory and invokes the startup function i.e. main(). Here, we can assume the OS is the caller of main() function. Therefore, the arguments can be passed to the main() function by specifying a list of values at the command line as shown below.

C:\tc\bin\> sum 10 20 30

Unlike other functions, the arguments to main() are passed in a different manner. They are passed as string constants. That means, even if we give integer values, they passed as string. In this case, the arguments passed as “sum”,  “10”, “20”, “30”.(passed as array of addresses to the main())

But main() receives two arguments, the fist argument is integer, which specifies the count of arguments including file name. The second argument is an array of addresses containing strings. Thus main() function should be defined as

                 void main(int argc, char *argv[])

argc      –    Number of arguments in the command line including program name
argv[ ]   –    holds addresses of all string constants that are passed to the program.

The input arguments should be separated by space or tab, but not with comma …etc.
  Program : The program receives integer numbers from command line and display the sum of them
main(int count, char *argv[])
int sum=0,i=0;
for(i=1;i<count; i++)
	sum=sum+atoi(a[i]);	// atoi() function converts numeric string to integer value
printf(“\n sum of numbers=%d”, sum);
Output :

C:\tc\bin\>sum 10 20 30 40
Sum of numbers=100

  Program :
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])   //  command line arguments
   printf(“Arguments passed through command line “ \ “not equal to 5”);
   return 1;
   printf(“\n Program name  : %s \n”, argv[0]);
   printf(“1st arg  : %s \n”, argv[1]);
   printf(“2nd arg  : %s \n”, argv[2]);
   printf(“3rd arg  : %s \n”, argv[3]);
   printf(“4th arg  : %s \n”, argv[4]);
   printf(“5th arg  : %s \n”, argv[5]);

return 0;
Output :

Program name: test
1st arg: this
2nd arg: is
3rd arg: a
4th arg: program
5th arg: (null)

We see you’re using an ad blocker.

Our website is made possible by displaying ads to our visitors.

Please help us continue to provide you with free. So please disabling your ad blocker.