Command Line Arguments in C – Don’t be Confused, be Practical!

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.

Recommended Reading – Functions in C Language 

Command Line Arguments in C

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
}

Join DataFlair on Telegram

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.

// The program name is cl.c
#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]);
}
return 0;
}

Code on Screen-

Command Line Arguments in C with Example

Output-

Command Line Arguments in C with result

Summary

In this tutorial, we understood the basic meaning of behind the command line arguments and its 2 components. We inferred that one is used to find the number of the command line argument and the other is used to find the list of command line arguments such as the program name.

Don’t forget to check 15 Types of Escape Sequence in C that make your Coding better

Suggestions and feedback are welcomed in the comment section!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.