...

/

Calling Functions

Calling Functions

Learn how to invoke functions.

We'll cover the following...

Calling refers to how a function is used in a code, i.e., how a function is invoked.

Coding example

Let’s take a look at how functions that have already been made are called in the main function.

Press + to interact
#include <iostream>
using namespace std;
void voidFunction(); // declaring a void function
int getSum(int, int); //declaring a function that takes two int arguments and returns their sum
int main()
{
int sum;
voidFunction(); //calling the function with the void return type.
sum = getSum(2,3); // calling the function getSum and saving the value returned in variable 'sum'
cout << "The value of sum is: " << sum << endl;
return 0;
}
void voidFunction() // writing the function definition
{
cout << "This is a void function!" << endl; // function only prints a string
}
int getSum(int num1, int num2) // writing the function definition
{
//the value 2 has been passed as num1
//the value 3 has been passed as num2
return num1 + num2; // returning the sum of num1 and num2
}

Explanation

  • First note the use of the two declarations that precede the main function. They allow main to use voidFunction and getSum even though they aren’t defined until after main.

  • The forward declarations ensure that the compiler knows that when it sees the symbols ...