next up previous
Next: Function Arguments Up: Overview of C++ Previous: Array Initialization

Functions

A C++ program is constructed from building blocks called functions. A function is a subroutine that contains one or more C++ statements nd perform one or more tasks. In well written C++ code, each function perform only one task. Each function has a name and it is this name that is used to call the function. In general, you can give a function whatever name you please. However, remember that main is reserved for the function which begins execution of your program.

So far we have been using only one function, main(), to write our programs. main() is the first function executed when your program begins to run, and it must be included in all C++ programs. The following program contains two functions main() and first().

Example
/* this program contains two functions */

#include <iostream.h>

int a, b, t;
int size;
size=7;

void first();// It can also be written as void first(void)
/* first() prototype declares the function prior to its definition which allows the compiler to know the function's return type and the its argument */
main()
cout << "The code is running statements in main()";
first();// Calling the function first()
cout << "The code is back in main();
return 0;
}
void first() //void means first is not returning a value to main
{
cout << "Code is executing statement in first()";
}

The program works like this. First, main() begins and it executes the first cout statement. Next main() calls first(). Notice how this is achieved: The functions name, first() appears followed by a semicolon. A function call is a C++ statement and must end with a semicolon. Next, first() executes its cout statement and then returns to main() at the line of code immediately following the call. Finally main() executes its second cout statement and then terminates. The output on the screen should be

The code is running statements in main() Code is executing statement in first() The code is back in main()

As you can see, first() does not contain a return statement. The keyword void, which precedes both the prototype for first() and its definition, formally states that first() does not return a value. In C++ functions that don't return values are declared as void.



 
next up previous
Next: Function Arguments Up: Overview of C++ Previous: Array Initialization
Yousef Haik
2/23/1998