Home >>C Tutorial >C Command Line Arguments

Command Line Arguments in C

Command Line Arguments in C

When the programs are executed then passing of some values from the command line to the C program is possible and these values are known as the command line arguments in C. When a programmer wants to control the program from the outside rather than hard coding those values inside the code then command line arguments are proven to be very important.

The handling of the command line arguments are done by the main() function arguments and the number of arguments passed is represented by argc and the argv[] that is a pointer, points to each arguments that are passed to the arguments.

Here is an example that will make it easy for you to understand the concept:

#include <stdio.h>

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

   if( argc == 2 ) {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 ) {
      printf("Too many arguments supplied.\n");
   }
   else {
      printf("One argument expected.\n");
   }
}
Output : $./a.out testing The argument supplied is testing

Generally, all the command line arguments are passed are separated by a space but in a situation where the argument already possess the space then that command line arguments can be passed by stuffing them either into double quotes "" or single quotes ''.

Here is an example regarding these quotes that will make help you in understanding this topic better:

Example

#include <stdio.h>
int main( int argc, char *argv[] )  {

   printf("Program name %s\n", argv[0]);
 
   if( argc == 2 ) {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 ) {
      printf("Too many arguments supplied.\n");
   }
   else {
      printf("One argument expected.\n");
   }

Output :
$./a.out "testing1 testing2"
Progranm name ./a.out
The argument supplied is testing1 testing2

No Sidebar ads