Functions and passing arguments.

A function is a block of code that can be executed many times by other functions or its self.

Function Basics.

You should already understand the concept of functions! If you don't, you are a sad sad man....

Might expand on this one day.

P.S. main() is a function.


Just like variables, all functions have to be declared before use. Here is an example.

        int add( int, int);

This statement declares a function called add, it has two integer arguments and returns an integer.


The definition is the meat of the function. Heres an example.

Passing values.

Passing values is known as call by value. You actually pass a copy of the variable to the function. If the function modifies the copy, the original remains unaltered. The previous example demonstarted call by value

Passing pointers.

This is known as call by reference and is an area worth spending some time on. We do not pass the data to the function, instead we pass a pointer to the data. This means that if the function alters the data, the original is altered.

Example of passing a pointer to a scalar.

C++ has a nice feature called reference variables which is a tider approch to modifing the contents of a passed variable.

Passing Arrays.

Example of passing a pointer to an integer array.

Example of passing a pointer to a two dimensional integer array.

Example of passing a pointer to a character array.

Example of passing a two dimensional character array.

Variable number of parms (...)

Example of passing an unknown number of variables to a function

Man page for va_start, va_end etc

Function recurssion.

Returning values.

Normally you would return an 'int', 'char', 'float', or 'double' using this technic. The obvious time to return a value would be to return a completion code.

Here is an example

The contents of 'c' are copied into 'i'.

Returning pointers.

Returning values is OK for the data types above but not very practical for 'char *' or structures. For these data types passing pointers can be more appropriate. When using these pointers it is important to understand the 'static' storage class otherwise you are going to get some unpredictable results.

Top Master Index Keywords Functions

Martin Leslie