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:

  • Command Line arguments
  • Components of command line arguments
  • C program to understand command line arguments

What are Command Line Arguments in C?

Command line arguments are nothing but 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.

Stay updated with latest technology trends
Join DataFlair on Telegram!!

Components of 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
.
.
}

Another way to implement command line arguments is:

int main( int argc, char **argv[] )
{
.
.
// BODY OF THE MAIN FUNCTION
.
.
}

Now, let us discuss the components of this code in detail:

  • 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.
  • agrv: It refers to “argument vector”. It is basically an array of character pointer which we use to list all the command line arguments.

C Program to Understand the Command Line Arguments in C

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;
}

If you’re still having any doubts related to the above syntax then don’t forget to check this

Quiz on Command Line Arguments in C

Summary

In this tutorial, we understood the basic meaning behind command line arguments and its 2 components.

We inferred that one is used to find the number of command line arguments and the other is used to find the list of command line arguments such as the program name.

Feel free to leave a comment below so that we could better understand your responses.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google | Facebook

1 Response

  1. Bhupesh says:

    How to pass number or value in argc and argv respectively

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.