C++: Basic Functions

Basic Functions

This C++ console lesson gives an introduction to using functions. A function is an independent piece of code that can be called from anywhere within the scope of the function's declaration. Like variables, functions have scope and the rules governing scope of functions operate similarly.

The advantage that functions offer comes in the form reusability and encapsulation. Instead of having to copy code blocks over and over again in a program, we can simply make a call to a function.

We can have simple functions like the one above, or we can have functions that take in arguments and/or a return value. This function takes two int arguments and returns an int.

The scope of argument variables is the entire function. So, for instance, we could use the variables iA and iB anywhere inside of the function block.

Functions can even call other functions. In this example, we have a function that counts from 1 to the passed in value. This function relies on another function to do the printing. Here the function "CountUpTo" relies on the function "PrintValue" so it must be in its scope.

Having functions, which rely on each other, can create scope dependencies, which are difficult or impossible to deal with using just function definitions like those above. So, we will usually want to separate the definition and the declaration from each other like this: