Functions

Chris Wild & Steven Zeil

Last modified: Jul 22, 2016
Contents:

The basic C++ language is relatively primitive. Its basic data types (integers, reals and characters) and operations on them (addition, subtraction, etc). are limited.

To build complex programs one needs to combine these primitive elements into larger building blocks. Then we compose the entire program from a combination of these building blocks.

In C++, functions are building blocks composed of groups of related statements.

Later in this course, we will look at modules, which are building blocks made from a combination of functions, variables, and data types. Eventually, we will see that the C++ class is a good way to implement most modules.

It’s even possible to go further. (Think back to our discussion in the orientation about scaling up to larger and larger projects.) We can combine classes into larger building blocks called namespaces, but we won’t get there in this course.

1 Functions

A function is a packaging of C++ statements into a unit which called as needed from elsewhere in the program.

For example,

void foo(); // declaration of foo
int bar(int i); // declaration of bar

These declarations tell the compiler (and you!) that these functions exist, what names you can use to invoke them, how many parameters they take and what the data types of those parameters are, and what kind of data these functions will return.

That’s pretty much all that you need to know in order to write a legal call to these functions and for the compiler to compile that call. Of course, it doesn’t tell you what those functions actually do, but that’s a separate issue.

A function signature is used by the compiler for handling function overload.

2 Example

// define a function that squares an integer number - a simple example to 
// illustrate the concepts
// function "square" takes on input parameter called "x" and returns the
// square of x
int square(int x)
{
 return x*x;
}

3 Syntax


// Function definition return-value-type function-name( named-parameter-list) { declarations-and-statements } // Function prototype return-value-type function-name( parameter-list); // Function signature function-name( parameter-list) // parameter-list is a comma separated ordered list of data types // named-parameter-list is a comma separated ordered list of data types, // parameter is given a name // The names of the parameters are only meaningful within the parameter // list and function definition. // That is, you can use any name without worrying if another program has // also used that name // the scope of a parameter name is limited to the function definition.

4 Tips

5 Overloading