Return To CS 110 Home

Colour Theme   Font Size Options
 
   
   
   
Intro to Functions

Introduction to Functions


Functions are a very important concept in C++. Every C++ program must have a main() function, which is what you have been using so far. The C++ compiler looks for the main function when it compiles the program and executes the code in it. If the main function is not found, a compiler error will occur. You already know the following format that is used for the main function.

    
int main() { . . . return 0; }

This function returns a single value 0. Thus, it is a value-returning function. The return data type is int. The statement return 0; is used to complete the function and the value 0 is returned to the operating system if the function has been processed correctly. The return indicates the end of the function.

Some functions we have used, such as .open() in InData.open() and get() in cin.get(), do not return any values. It is only the name of an action. These kind of functions are called void functions.

The C++ system includes a standard library - a large collection of prewritten functions, data types, and other items that any C++ programmer may use. To use library functions, you have to place an #include directive near the top of the program, specifying the header file. For example, to use cin and cout, you have to have #include<iostream> in your program; to use sqrt(x) and pow(x, y) functions, you have to have #include<cmath> in your program.

In this lab, we focus on user defined functions.

In this class, user defined functions are broken into three parts:

  1. Function prototypes - In order to prepare the program for user defined functions, you need to forward declare the functions at the top of your program by providing a function prototype. The function prototype includes the return type, function name, and parameters, but does not define what the function will do. Without this, the program won't know the function exists, and throw an error when the program runs because there is an unrecognized function call.

    The general syntax of a function prototype is:

        
    returnDataType functionName(Parameter_DataType_List);
  2. Function call - The code that will activate the user defined function from within the program, such as in the main function. If the prototype had parameters, the function call will need to provide the data to pass to the function
  3. Function definition - At the bottom of the file, we write the code for the actions the functions will perform, such as arithmetic or printing output.
            
    returnDataType functionName(ParameterList) { // Statements . . . }

When writing functions, the prototype and definition need to match exactly, and the function call needs to provide the same amount of parameters to work.

Consider the following example program: