Command-line Arguments

In an environment such as UNIX and the MS DOS Window, the user executes a program by entering the program name in a command-line.  For a C program, optional fields entered after the program name are passed to the program as data.  The optional fields are referred to as command-line arguments, although as explained below, they are not handled in the usual way of arguments in a function call.

The environment performs the following steps in executing the program.  First, it scans the command-line and identifies the character strings delimited by blanks that represent the program name and any optional data.  Then, it assembles an array consisting of pointers to these strings, in order of their occurrence in the command-line, and an additional final null pointer.  Finally, to execute the program, it invokes main in the manner of a function call with two arguments.  The first called argc, for argument count, is a count of all the elements in the pointer array, except for the final null pointer.  The second called argv, for argument vector, is a pointer to the first element in the pointer array.

For the following entry on the command-line:

    verify pswd1 pswd2 pswd3

The environment would assemble the following data (in C format for this example).

    int argc = 4;
    char *argv[] = {"verify", "pswd1", "pswd2", "pswd3", NULL};

Then, it would execute the program in the manner of a function call with two arguments: the array count integer, and the pointer array name.

    verify(argc, argv);

The definition of the main function, with parameters correponding to the calling arguments is usually found as follows.

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

A more precise definition of main reflecting the true nature of argv is often found.

int main(int argc, char **argv) {}

Copyright © 2018 The Stevens Computing Services Company, Inc.  All rights reserved.