                   Passing Parameters To A C Program


                            Matthew Probert
                           Servile  Software


A C program may receive a variable number of parameters from the 
command line. The number of received parameters is recorded by the 
"start-up" code in the main() function parameter 'argc' and each 
parameter is stored as a null terminated string in the array parameter  
'argv[]'. 

These parameters are optional, if you declare your main() function 
without parameters, then the program will not be able to directly 
receive parameters from the command line when it starts up.

The first parameter supplied to the C program is the name of the 
C executable program and it's path, for example:

        c:\borlandc\myprog.exe

This is always argv[0]. Command line supplied parameters then start at 
argv[1] and continue from there. The following small program 
illustrates how parameters may be read from argv[] and used to set 
program variables. Three variables: P1, P2 and P3 are declared. P1 
will be set to 1 if the parameter -A is entered. P2 will be set if -B 
is entered and P3 will be set to 1 if -C is entered. The order in 
which these parameters is supplied is irrelevant.

For example:

        myprog -B -A

Will set P1 and P2 to 1, leaving P3 at 0.

        myprog -A -C

Will set P1 and P3 to 1, leaving P2 at 0.

This is a simple technique, but a useful one for allowing a user of 
the program to supply switches in any order. The switches could be 
made case insensitive by replacing strcmp() with stricmp().


----------------------------Cut Here----------------------------
#include <stdio.h>
#include <string.h>

void main(int argc, char *argv[])
{
    int p1;
    int p2;
    int p3;

    int counter;

    /*
        Display each received parameter in order
    */
    for(counter = 1; counter < argc; counter++)
    {
        printf("\nParameter %d  %s",counter,argv[counter]);
    }

    p1 = p2 = p3 = 0;


    /*
        This shows how parameters can be accepted in any
        order and used to set program variables
    */

    for(counter = 1; counter < argc; counter++)
    {
        if (strcmp(argv[counter],"-A") == 0)
            p1 = 1;
        else
        if (strcmp(argv[counter],"-B") == 0)
            p2 = 1;
        else
        if (strcmp(argv[counter],"-C") == 0)
            p3 = 1;
    }

    /*
        Display program variable values
    */
    printf("\nP1  %d\nP2  %d\nP3  %d",p1,p2,p3);
}
----------------------------Cut Here----------------------------

