×

C - Command line arguments


In this chapter, we will learn command line arguments in C.


What are command line arguments?

The command line arguments are the input or the values supplied to the program from console. Command line arguments can be used to accept various inputs for the program, for instance, we can get the maximum limit of memory to be used by our program from the console.


How to pass command line arguments to a c program?

There are two parameters that are used to pass command line arguments to a c program. These are argc and argv. These two are the arguments of the main() function.

argc

The argc parameter holds the total number of arguments on the command line. argc is an integer type of argument. The name of the program is also considered as the first argument and hense the value of argc will be at least 1 in any case.

argv

argv parameter is the array parameter. It is of string pointer type. It is a pointer array that points to every argument passed to the program. Since it is an array pointer, the value can be accesed as any normal array by specifying the index. The basic declaration of argv and accessing the values is as follows

char *argv[];
program_name = argv[0];
// Index 0 of argv array refers to the name of the program
argument1 = argv[1];
//Index 1 refers to the first argument passed after the program name 

Command line argument example

To understand command line arguments much better, lets write a simple C program to illustrate the use of command line arguments.

File name: command_line_example.c
/* Command line arguments in C */
#include<stdio.h>
int main(int argc, char *argv[])
{
    printf("\n The name of the program is : %s", argv[0]);
    printf("\n Total number of argument supplied are : %d", argc);
    printf("\n They are :");

    printf("\n Argument 1 = %s", argv[0]);
    for(int i=1; i<argc; i++){
        printf("\n Argument %d = %s", i+1, argv[i]);
    }
    printf("\n That's it. Isn't that easy? \n");
    return 0;
}
            
Compiling
gcc command_line_example.c

Lets see the output of the above program when No arguments are supplied.

Executing without arguments
./a.out
Output 1
The name of the program is : ./a.out
Total number of argument supplied are : 1
They are :
Argument 1 = ./a.out
That's it. Isn't that easy?
            

Now Let's see the output of the same program when the arguments are supplied. We will supply 3 arguments namely: Earth, Coding and Learning.

Executing with command line arguments
./a.out Earth Coding Learning
Output 2
The name of the program is : ./a.out
Total number of argument supplied are : 4
They are :
Argument 1 = ./a.out
Argument 2 = Earth
Argument 3 = Coding
Argument 4 = Learning
That's it. Isn't that easy?
            

Congratulations!!! You have completed basic C programming tutorial on Earth Coding. From here you can now take your skills to the next level by learning Data Structures.