C++ Topic
Command Line Processing


Invoking a Program with Command-Line Arguments

For those of you who have worked in Unix or a Command Prompt window under Windows, you have probably entered a command such as:
cd assignment1
		
i.e., a command to change the current working directory to assignment1. The above coomand actually consists of two components: Running the command can thus be thought of as analogous to calling a function-- in both cases This is not a coincidence-- in essence your program is viewed by the operating system as just another function to be called. There obviously is more going on than a simple function call within a program: but eventually the OS does indeed make a function call to the program's entry point (which for our purposes is the main function).

(As an aside, similarly, the program returns to the OS in much the same way, as can be seen from the return statement in main. The return value is information passed back by the program to the OS about the success/failure of the program, and is called the program exit status.)

Thus, we see that a program can be invoked with arguments that provide information to the program from the user. We call these command line arguments.

In order for this information to be of any value to the program, we must be able to access the command line arguments from within the program.

Accessing the Command Line Arguments From the Program

As we saw above, the command line consists of The user types the program name and arguments on the command line, and the operating system then parses the command line, breaking it up to it individual parts-- the program name and each argument (where again, for our purposes, the arguments are separated by whitespace). Each of thses components-- the program name and the individual arguments-- are treated as a C-like string (char *) by the OS, placed into an array of such string (i.e., char *[] or, equivalently, char **