C – Command Line Arguments

In C language, you can pass values from the command line. The arguments are placed after the program name at the time of execution. For command line arguments, set the main() function in C Language to the following, wherein argc is used to count the arguments and argv has all the arguments:

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

Display the Command Line Arguments in C

Let us see an example:

#include <stdio.h>  

int main(int argc, char *argv[] )  {  
  
   printf("Displaying the command line arguments...");  
   
   printf("\nFirst argument = %s\n", argv[1]);  
   printf("First argument = %s\n", argv[2]);  
   printf("First argument = %s\n", argv[3]);  
   printf("First argument = %s\n", argv[4]); 
   return 0;
}

Output

The output when we have set the command line arguments as A, B, C, D:

Displaying the command line arguments...
First argument = A
First argument = B
First argument = C
First argument = D

Count the Command Line Arguments in C

The argc in the following syntax is used to count the command line arguments in C Language:

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

Let us see an example:

#include<stdio.h>

int main(int argc, char *argv[] )  {  
  
   printf("Displaying the command line arguments...\n");  
   
   printf("Count of arguments = %d\n", argc);  
    
   printf("\nFirst argument = %s\n", argv[1]);  
   printf("First argument = %s\n", argv[2]); 
   printf("Third argument = %s\n", argv[3]);  
   printf("Fourth argument = %s\n", argv[4]);  
   
   return 0;
}

Output

The output when we have set the command line arguments as A, B, C, D:

Displaying the command line arguments...
Count of arguments = 5

First argument = A
First argument = B
Third argument = C
Fourth argument = D

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others:


For Videos, Join Our YouTube Channel: Join Now


Read More:

C - Typecasting
C - Unions
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment