C - main() Function

Introduction

The main() function is where execution starts.

main() can have a parameter list so that you can pass arguments to main().

You can write the main() function either with no parameters or with two parameters.

The first parameter is of type int and represents a count of the number of arguments, including the name of the program itself.

The second parameter to main() is an array of pointers to strings.

The argument passed when you write two arguments following the name of the program at the command line will be an array of three pointers.

The first will point to the name of the program, and the second and third will point to the two arguments you enter at the command line:

#include <stdio.h>
int main(int argc, char *argv[])
{
  printf("Program name: %s\n", argv[0]);
  for(int i = 1 ; i<argc ; ++i)
    printf("Argument %d: %s\n", i, argv[i]);
  return 0;
}

argv[0] is the program name.

Subsequent elements in the argv array will be the arguments that were entered at the command line.

You can use double quotes to mark a single argument which has space inside.

All command-line arguments will be read as strings.

You can use one of the functions shown in the following table to convert string to numbers.

Function Description
atof()Converts the string passed as an argument to type double
atoi()Converts the string passed as an argument to type int
atol()Converts the string passed as an argument to type long
atoll() Converts the string passed as an argument to type long long

The following code shows how to convert a command-line argument to an integer:

int arg_value = 0;           // Stores value of command line argument
if(argc > 1)                 // Verify we have at least one argument
  arg_value = atoi(argv[1]);
else
{
  printf("Command line argument missing.");
  return 1;
}

Related Topics

Exercise