Functions

Functions are a reusable bit of code that can be called anywhere in your program.

Function Declarations


A C++ function declaration looks like the code below:
void MyFunction()
{
//function code goes here.
}

The first word indicates the type of the return value, and is followed by the name, which in this case is "MyFunction".  The function above doesn't return any value, so void is used for the return type. We can put any code inside the function.  The example below declares a function called "SayHello" which prints the string "Hello!" whenever it is called.  Note that the function code only gets called when the function is called.  The function code is not executafed before then::

void SayHello()
{
Print("Hello!")
}

SayHello();


Function Arguments


You can pass optional values to a function to be used in its code.  These values are called "arguments" or "parameters".  In the example below, a function is declared which accepts one argument and performs an action:
void PrintUpper(std::string text)
{
Print(std::toupper(text));
}

PrintUpper("Functions can be fun.");

You can send multiple arguments to a function by separating them with a comma:

void CombineAndPrintUpper(std::string text1, std::string text2)
{
Print(std::toupper(text1+text2));
}

CombineAndPrintUpper("Hello, ","how are you?");


Return Values


Functions can also return a value to the code that is calling them.  The function below accepts an argument, adds one to it, then returns the result. Notice the return type of this function is an integer value:
int AddOne(num)
{
return num+1;
}

int n = AddOne(2);
Print(n);


Conclusion


Functions in C++ are actually pretty simple! In practice, we will make all our functions part of a class, which we will learn next. Soon you will feel the full power of the C++ programming language!