In C++, functions are reusable blocks of code that perform specific tasks and can be invoked from other parts of the program.
Functions allow dividing code into more manageable fragments (this allows us to create more reusable code and improve the program’s readability and maintainability).
If you want to learn more, check out the Introduction to Programming Course
What is a function
A function in C++ is a set of instructions that performs a specific task. A function can be defined to receive certain parameters, process this data, and return a result if necessary. The basic structure of a function in C++ is as follows:
return_type function_name(parameter_type parameter1, parameter_type parameter2, ...)
{
// Function code
return return_value; // Optional
}
- Return type: This is the type of value the function returns. It can be any data type, such as
int,double,char, etc. If the function does not return any value,voidis used. - Function name: This is the function’s identifier. It must be unique within the scope where it is defined.
- Parameter list: These are variables passed to the function so it can operate with this data (Parameters are optional, and a function may have no parameters)
- Function code: This is the block of code that executes when the function is called.
- Return value: This is the result the function returns, if applicable. The
returnstatement is used to return a value.
Basic example
Let’s look at a basic example of a function in C++ that adds two numbers:
#include <iostream>
int Add(int num1, int num2) {
return num1 + num2;
}
int main() {
int result = Add(5, 3);
std::cout << "The sum is: " << result << std::endl;
return 0;
}
In this example:
- The
Addfunction takes two parameters (num1andnum2), performs the addition operation, and returns the result. - In
main, theAddfunction is called with the values5and3, and the result8is printed to the console.
Calling functions
To call a function, you simply use its name followed by parentheses containing the necessary arguments (if any). Here is an example of calling the Add function:
int result = Add(5, 3);
This line,
- Calls the
Addfunction with the values5and3 - Stores the result in the variable
result
Parameters
Functions in C++ can accept parameters, which are values passed to the function for it to process. These parameters are defined in the function declaration and are used inside the function to perform calculations or manipulations.
For example, the following function calculates the area of a rectangle given its width and height:
double CalculateRectangleArea(double width, double height) {
return width * height;
}
In this function, width and height are the parameters used to calculate the rectangle’s area.
Return value
Functions can return a value using the return keyword. The type of value returned must match the return type specified in the function declaration.
For example, the following function calculates the area of a circle given its radius:
#include <cmath> // For the constant M_PI
double CalculateCircleArea(double radius) {
return M_PI * radius * radius;
}
The CalculateCircleArea function returns the area of the circle using the M_PI constant from the cmath library.
Functions without return
If a function does not return any value, the return type void is used. These functions are generally used to perform actions without needing to return a result.
For example, a function that prints a message to the console:
void PrintMessage(const std::string& message) {
std::cout << message << std::endl;
}
Here, PrintMessage does not return any value; it simply prints the provided message.
Inline functions
inline functions suggest to the compiler to expand the function’s code at the call site (instead of making a normal function call). This can improve performance for small, frequently called functions.
inline int sum(int a, int b) {
return a + b;
}
inline is a “suggestion” to the compiler. Ultimately, the compiler may decide to ignore it, or apply it to functions (even without us specifying it)
Recursive functions
A function is recursive if it calls itself. Recursion is useful for solving problems that can be divided into smaller subproblems of the same type.
#include <iostream>
int factorial(int n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int number = 5;
std::cout << "The factorial of " << number << " is " << factorial(number) << std::endl;
return 0;
}
Practical examples
Function to determine if a number is even or odd
This function determines if a number is even or odd:
std::string EvenOdd(int number) {
if (number % 2 == 0) {
return "even";
} else {
return "odd";
}
}
Function to calculate the area of a circle
This function calculates the area of a circle given its radius:
#include <cmath> // For the constant M_PI
double CalculateCircleArea(double radius) {
return M_PI * radius * radius;
}
Function to determine the maximum of two numbers
This function returns the larger of two numbers:
int Maximum(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
Function to convert degrees Celsius to Fahrenheit
This function converts a temperature from degrees Celsius to degrees Fahrenheit:
double CelsiusToFahrenheit(double celsius) {
return (celsius * 9 / 5) + 32;
}
Function to check if a number is prime
This function determines if a number is prime:
bool IsPrime(int number) {
if (number <= 1) return false;
for (int i = 2; i < number; i++) {
if (number % i == 0) return false;
}
return true;
}
Function to calculate the sum of an integer array
This function calculates the sum of all elements in an integer array:
#include <vector>
int SumArray(const std::vector<int>& numbers) {
int sum = 0;
for (int number : numbers) {
sum += number;
}
return sum;
}
These examples show how to define and use functions in C++. This does not mean they are always the best way to solve all problems; in some cases, there may be more suitable solutions.
