CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

C Programming: Passing arguments (command-line arguments) to an application

In ‘C’ programming we can pass arguments to an application or a program. We can call this as passing command-line arguments. I know you will ask the question “How to pass them?”. Good. Fortunately it is simple.

As you aware, main() is the function where the execution of the program starts in ‘C’ programming. That means, if you have written an application using ‘C’; and the application is an executable; it should have main() function. And when you run this application; the execution will starts from main().

The syntax of main() is:

{void | int} main([int argc, char *argv[]]);

main() should either return an int value or should not return anything. The arguments “int argc” and “char *argv[]” are optional. These arguments are used only when you pass any arguments to the application.

“int argc” tells the number of arguments passed to the application. “char *argv[]” is an array of those arguments.

How to pass arguments to main()?

At the time of invoking the application; you need to pass these arguments. For eg: your application name is “sample.out”, you should pass “./sample.out 1 Hello”. Here “1” and “Hello” are the arguments.

Let us take a simple example:

//sample.c
#include <stdio.h>

void main(int argc, char *argv[])
{
   int i = 0;

   printf("Hello! You have passed (%d) arguments.\n", argc);

   printf("The arguments are:\n");
   
   for ( i = 0 ; i < argc ; i++ )
       printf("%s\n", argv[i]);

   printf("\n");
}

From above code; we are displaying number of arguments we passed to our program and displaying each argument in separate line. As discussed above, argc is meant for number of arguments and argv holds those actual arguments. Using these we are displaying actual arguments we passed to our program. Observe that the arguments index starts from “0” and first argument is always the program itself. For eg: if you call “./sample.out 1 Hello”; ./sample.out will be the first argument, 1 and Hello are the 2nd & third arguments respectively.

Compile the application and before you run the application run it as:

./sample.out 1 Hello

The application will display below result:

$ ./sample.out 1 Hello
Hello! You have passed (3) arguments.
The arguments are:
./sample.out
1
Hello

Our program displaying 3 arguments. One is the program itself and “1” and “Hello” are the other arguments.

Passing arguments to the application is really helpful. It allows to change the behavior of an application by passing command-line arguments.

// Malin

C Programming: Passing arguments (command-line arguments) to an application

Leave a Reply

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

Scroll to top