Argument Definitions

The arguments in the prototype

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

or

int wmain( int argc[ , wchar_t *argv[ ] [, wchar_t *envp[ ] ] ] );

allow convenient command-line parsing of arguments and, optionally, access to environment variables. The argument definitions are as follows:

argc

An integer that contains the count of arguments that follow in argv. The argc parameter is always greater than or equal to 1.

argv

An array of null-terminated strings representing command-line arguments entered by the user of the program. By convention, argv[0] is the command with which the program is invoked, argv[1] is the first command-line argument, and so on, until argv[argc], which is always NULL. See Customizing Command Line Processing for information on suprressing command-line processing.

The first command-line argument is always argv[1] and the last one is argv[argc – 1].

Microsoft Specific

envp

The envp array, which is a common extension in many UNIX® systems, is used in Microsoft C++. It is an array of strings representing the variables set in the user’s environment. This array is terminated by a NULL entry. See Customizing Command Line Processing for information on suprressing environment processing. This argument is ANSI compatible in C, but not in C++.

END Microsoft Specific

The following example shows how to use the argc, argv, and envp arguments to main:

#include <iostream.h>
#include <string.h>

void main( int argc, char *argv[], char *envp[] )
{
    int iNumberLines = 0;    // Default is no line numbers.

    // If more than .EXE filename supplied, and if the 
    // /n command-line option is specified, the listing
    // of environment variables is line-numbered.

    if( argc == 2 && stricmp( argv[1], "/n" ) == 0 )
        iNumberLines = 1;

    // Walk through list of strings until a NULL is encountered.
    for( int i = 0; envp[i] != NULL; ++i )
    {
        if( iNumberLines )
            cout << i << ": " << envp[i] << "\n";
    }
}