...

/

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. To call a function, you write its name followed by the comma-separated list of actual input values in parentheses.

Code example

Let’s see how the existing functions are called in the main function.

Press + to interact
C++
#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 ...