9. Functions

Much of what we’ve shown you so far has been introducing the building blocks of coding in C++; you’ve seen several different data types, common iteration methods (the multiple kinds of loops), and a versatile container, the vector type. With this knowledge, you can now do many things in C++. But what kinds of things can you write? And how are they useful?


One of the most powerful tools of coding is that we can create functions to perform certain calculations or actions for us at will. We can call functions whenever we want after we define the function itself, which allows us a great deal of flexibility in using it. We have to define functions just like we do variables, so the C++ compiler knows what we want something with our function name to do. Below is an example of a function with the majority of the body omitted so you can see the different parts of a function definition and how the return works.

This is the outline of a function, with it’s five necessary components marked in the red bubbles - below are explanations for each component:






Now that we’ve looked at how to define a function, let’s look at how to call it later in our program. For this example, we assume that the stdev function has been completed, i.e., the comment in the previous code snippet was replaced with all the code needed to make the function work. The function itself works using concepts beyond the scope of this introduction to C++, so we’ll move forward assuming that it works as intended.

In this code snippet, we have the main program that would run after (and only after) the definition of the stdev function, otherwise the program crashes and tells us in the error message that “stdev is not declared in this context”. In it, we create a vector of doubles called “vExample” and then call the stdev function using it. We define a variable to hold the value of the function’s output which must be a double since that is the function’s return type, and call the function using the ( ) operand. The function only needs one input that must be a vector of doubles, so we pass vExample as a parameter. The program will then execute the code contained within the function and then return the final value to main. The last thing we do is cout the value from the stdev function, which outputs to the console the calculated standard deviation: