Intermediate Business Programming with C++

main( ) and its Arguments

The function main( ) like other functions may have arguments. In most applications, no arguments are listed and therefore its signature is void. However, in some cases it is desirable that main( ) have a non void signature consisting of an int: argc and an array of character pointers: argv When main( ) has a non void signature, its construct is:

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

The arguments: argc & argv are not keywords but traditional programmer words instead. The first will contain the number of strings that appear on the command line. The second variable is an array of pointers whose size is the first argument: argc.

For example, the following line of code will call Window's NOTEPAD program when typed in at the command line. It will load the source file TEST.CPP into the program NOTEPAD:

NOTEPAD.EXE TEST.CPP

In this case, argc is 2 and argv is an array of pointers the first of which points to the array: "NOTEPAD.EXE" and the second points to the array: "TEST.CPP"

See MAINARG.CPP

Passing Arguments by Value

When a function is called, the variable placed as an argument does not itself pass into the function's body. Instead the value of the variable is placed on the stack for each call of the function. The body may then remove the value when required by the code. We therefore call this: passing by value See BYVALUE.CPP

Passing by value has several undesirable characteristics to include that it:

One solution to these problems is to use: global variables. The advantages of global variables are:

While global variable may appear to be helpful characteristics, there may also be harmful ones as well because global variables:

Therefore another solution to global variable may be required.

Passing and Returning by Reference

A reference of a variable has been discussed in the notes above. A reference of a variable is another name for the variable. References may be used as arguments of functions called passing by reference as in the following functional prototype:

void swap(int & , int &);

When the reference operator is used, it appears in the prototype and in the definition of the function but not in the call. See BYREF.CPP. Notice that the reference operator does not appear in the function call.

When a reference is used with an argument:

A problem that may occur with references is that since the operator does not appear in the call, someone reading the code may not realize that the argument may be changed.

Passing and Returning Pointers

A process similar to passing by references is called passing by pointers. In this case pointers are used as arguments of functions. Passing by a pointer is different from passing by reference in that

Passing by reference is closer to passing by a constant pointer.

Passing by pointers is different from passing by value because it permits:

See MONEY.CPP and see NEWNAME.CPP

Категории