C - main() Function Arguments

Introduction

The following code accesses the command line parameters.

#include <stdio.h> 

int main(int argc, char *argv[]) 
{ 
      if(argc>1) 
          printf("Greetings, %s!\n",argv[1]); 
      return(0); 
} 

The main() function now shows its two arguments, argc and *argv[].

It uses the int value argc to determine whether any additional items were typed after the program name at the command prompt.

It uses the string value (char array) argv[1] to display the first item after the program name at the command prompt.

You can run the program like this:

Main i1 

The code uses only the first command-line argument, so if you type more, they're ignored.

In the preceding line, only i1's name appears in the output.

When you don't plan on your program accepting any command line arguments, you can leave the main() function's parentheses empty. Like this:

int main() 

When arguments are used in your code, they must be declared.

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

argc is the argument count value. It's an integer that ranges from 1 through how many items were typed after the program name at the command prompt.

*argv[] is an array of char pointers. You can think of it as an array of strings.

The following code counts the number of arguments typed at the command line. That value, argc, is displayed.

Demo

#include <stdio.h> 

int main(int argc, char *argv[]) 
{ 
    printf("You typed %d arguments.\n",argc); 
    return(0); //from  w  w w.  ja v  a 2  s  . c  o m
}

Result

The main() function receives information about the command-line argument directly from the operating system.

The command line is evaluated, and arguments are tallied and referenced.

The program name itself is considered the first argument. You can prove it by adding a single line to the code:

printf("That argument is %s.\n",argv[0]); 

Related Topic