In C++, functions are reusable code blocks that perform specific tasks and can be invoked from other places in the program.
Functions allow us to break the code into more manageable chunks (this allows us to create more reusable code and improve the readability and maintainability of the program).
If you want to learn more about Functions
check out the Introduction to Programming Course read more
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 these 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: It is the type of value that the function returns. It can be any data type, such as
int
,double
,char
, etc. If the function does not return any value,void
is used. - Function name: It is the identifier of the function. It must be unique within the scope in which it is defined.
- Parameter list: These are variables that are passed to the function so that it can operate with this data (Parameters are optional and a function may have no parameters)
- Function code: It is the block of code that is executed when the function is called.
- Return value: It is the result that the function returns, if applicable. The
return
statement 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 function
Add
takes two parameters (num1
andnum2
), performs the addition operation, and returns the result. - In
main
, the functionAdd
is called with the values5
and3
, and the result8
is printed to the console.
Calling functions
To call a function, 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 function
Add
with the values5
and3
- Stores the result in the variable
result
Parameters
Functions in C++ can accept parameters that are values passed to the function for it to process. These parameters are defined in the function declaration and are used within 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 area of the rectangle.
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 function CalculateCircleArea
returns the area of the circle using the constant M_PI
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 the need 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 performing a normal call). This can improve performance in small, frequently invoked 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 indicating 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 greater of two numbers:
int Maximum(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
Function to convert 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 array of integers
This function calculates the sum of all elements in an array of integers:
#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++. It does not mean that they are always the best way to solve all problems; in some cases, there may be more suitable solutions.