Functions in C++ are building blocks for modular and reusable code. They allow you to encapsulate code logic, make programs more readable, and enable code reuse. This tutorial covers a wide range of examples, illustrating different use cases for functions in C++.
Examples for Function in C++
1. Basic Function Example
A simple function to add two numbers and return their sum.
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
cout << "Sum: " << add(10, 20) << endl;
return 0;
}
Output
Sum: 30
Explanation
The function int add(int a, int b)
is a simple C++ function that takes two integer parameters, a
and b
, adds them together, and returns their sum as an integer.
The return type of the function is specified as int
, indicating that the function’s result will be an integer value.
The parameters a
and b
are placeholders for the two numbers that will be provided when the function is called.
The function body contains the statement return a + b;
, which computes the sum of a
and b
and returns the result to the calling function.
In summary, the add
function encapsulates the addition operation for reusability.
2. Function with No Parameters and No Return Value
A function that prints a message without taking any input or returning a value.
#include <iostream>
using namespace std;
void printMessage() {
cout << "Hello, World!" << endl;
}
int main() {
printMessage();
return 0;
}
Output
Hello, World!
Explanation
The function void printMessage()
is a simple C++ function that does not take any parameters and does not return any value. The return type of the function is void
, indicating that it performs an action without producing a result.
The function name printMessage
reflects its purpose: to print a message to the console.
The function body contains the statement cout << "Hello, World!" << endl;
, which outputs the text Hello, World!
to the console and moves the cursor to a new line.
3. Function with Default Parameters
A function that greets the user, using a default name if no argument is provided.
#include <iostream>
using namespace std;
void greet(string name = "Guest") {
cout << "Hello, " << name << "!" << endl;
}
int main() {
greet();
greet("Alice");
return 0;
}
Output
Hello, Guest!
Hello, Alice!
Explanation
The function void greet(string name = "Guest")
uses default parameters. The return type is void
, indicating that the function does not return a value.
The parameter name
is of type string
and has a default value of "Guest"
. This means that if no argument is provided when the function is called, the value "Guest"
will be used.
The function outputs a personalized greeting to the console using the statement cout << "Hello, " << name << "!" << endl;
.
For example, calling greet()
will print Hello, Guest!
, while calling greet("Alice")
will print Hello, Alice!
.
4. Function with Reference Parameters
A function that swaps two integers using reference parameters.
#include <iostream>
using namespace std;
void swap(int& x, int& y) {
int temp = x;
x = y;
y = temp;
}
int main() {
int a = 10, b = 20;
swap(a, b);
cout << "a: " << a << ", b: " << b << endl;
return 0;
}
Output
a: 20, b: 10
Explanation
The function void swap(int& x, int& y)
is a C++ function that demonstrates the use of reference parameters.
The return type is void
, indicating that the function does not return a value.
The parameters x
and y
are passed by reference using the &
symbol, which means the function works directly with the original variables provided as arguments. This allows the function to modify the actual values of x
and y
.
Inside the function, a temporary variable temp
is used to store the value of x
. The value of x
is then assigned to y
, and the value stored in temp
is assigned back to y
. As a result, the values of x
and y
are swapped.
5. Function Returning a Pointer
A function that returns a pointer to a static variable.
#include <iostream>
using namespace std;
int* getStaticValue() {
static int value = 42;
return &value;
}
int main() {
int* ptr = getStaticValue();
cout << "Value: " << *ptr << endl;
return 0;
}
Output
Value: 42
Explanation
The function int* getStaticValue()
is a C++ function that demonstrates how to return a pointer from a function.
The return type is int*
, indicating that the function returns a pointer to an integer.
Inside the function, a static variable value
is declared and initialized to 42
. The static
keyword ensures that the variable retains its value between function calls and persists in memory throughout the program’s execution.
The statement return &value;
returns the memory address of the variable value
. This allows the caller to access or manipulate the value stored at that memory location.
6. Recursive Function
A function that calculates the factorial of a number using recursion.
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
cout << "Factorial of 5: " << factorial(5) << endl;
return 0;
}
Output
Factorial of 5: 120
Explanation
The function int factorial(int n)
is a C++ function that demonstrates recursion, where a function calls itself to solve a problem.
The return type int
indicates that the function returns an integer value.
The parameter n
represents the number for which the factorial is to be calculated.
The base case is defined as if (n == 0 || n == 1)
, which returns 1
, since the factorial of 0
and 1
is 1
. For other values of n
, the function recursively calls itself with n - 1
until it reaches the base case. Each recursive call calculates n * factorial(n - 1)
, effectively multiplying all integers from n
down to 1
.
7. Inline Function
An inline function to calculate the square of a number.
#include <iostream>
using namespace std;
inline int square(int x) {
return x * x;
}
int main() {
cout << "Square of 4: " << square(4) << endl;
return 0;
}
Output
Square of 4: 16
Explanation
The function inline int square(int x)
is a C++ inline function that calculates the square of an integer. The inline
keyword suggests to the compiler that the function’s code should be expanded in place wherever it is called, instead of making a function call.
The return type int
indicates that the function returns an integer value.
The parameter x
is an integer whose square is to be computed.
The function body contains the statement return x * x;
, which multiplies x
by itself and returns the result.
8. Overloaded Functions
Functions with the same name but different parameter types.
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int main() {
cout << "Int sum: " << add(10, 20) << endl;
cout << "Double sum: " << add(5.5, 4.5) << endl;
return 0;
}
Output
Int sum: 30
Double sum: 10
Explanation
The provided code demonstrates function overloading in C++, where multiple functions share the same name but differ in their parameter types or numbers.
The first function int add(int a, int b)
takes two integers as input and returns their sum as an integer.
The second function double add(double a, double b)
takes two double-precision floating-point numbers as input and returns their sum as a double.
The main()
function showcases the use of these overloaded functions. The statement add(10, 20)
calls the integer version of the add
function, producing an integer sum, while add(5.5, 4.5)
calls the double version, producing a floating-point sum.
9. Lambda Functions
Using lambda expressions as anonymous functions.
#include <iostream>
using namespace std;
int main() {
auto add = [](int a, int b) {
return a + b;
};
cout << "Sum: " << add(10, 20) << endl;
return 0;
}
Output
Sum: 30
Explanation
A lambda function is an anonymous function that can be defined inline and used immediately. In this example, the lambda function is assigned to the variable add
using the auto
keyword, which automatically deduces the type. The lambda function takes two integer parameters, a
and b
, and returns their sum using the statement return a + b;
. The add
lambda is then called with arguments 10
and 20
, and the result is printed to the console.
10. Function with Constant Parameters
A function that ensures parameters are not modified.
#include <iostream>
using namespace std;
void displayMessage(const string& message) {
cout << "Message: " << message << endl;
}
int main() {
string text = "Hello, C++!";
displayMessage(text);
return 0;
}
Output
Message: Hello, C++!
Explanation
The function void displayMessage(const string& message)
is a function that uses constant parameters. The parameter message
is declared as a constant reference using const
and &
, ensuring that the function cannot modify the value of message
. This enhances safety and efficiency, especially when working with large objects like strings, as it avoids making a copy of the parameter. The function’s purpose is to print the provided message to the console using the statement cout << "Message: " << message << endl;
.
Since the parameter is constant, the function guarantees that the input data remains unchanged, making it suitable for scenarios where the function should only read the data without altering it.
11. Function as a Parameter
Passing a function as an argument to another function using function pointers.
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int compute(int x, int y, int (*operation)(int, int)) {
return operation(x, y);
}
int main() {
cout << "Result: " << compute(10, 20, add) << endl;
return 0;
}
Output
Result: 30
Explanation
The function int add(int a, int b)
takes two integers, adds them, and returns their sum.
The function int compute(int x, int y, int (*operation)(int, int))
accepts two integer parameters x
and y
, and a function pointer operation
that points to a function with the signature int (int, int)
. Inside compute
, the operation
function pointer is invoked with x
and y
as arguments, allowing dynamic selection of the operation to perform.
In the main()
function, compute
is called with 10
, 20
, and the add
function as arguments. The result of add(10, 20)
is computed and printed as Result: 30
.
12. Function with Arrays as Parameters
A function that calculates the sum of elements in an array.
#include <iostream>
using namespace std;
int calculateSum(const int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; ++i) {
sum += arr[i];
}
return sum;
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
cout << "Sum: " << calculateSum(numbers, 5) << endl;
return 0;
}
Output
Sum: 15
Explanation
The function int calculateSum(const int arr[], int size)
uses arrays as parameters.
The parameter arr
is a constant integer array, indicated by const
, which ensures that the function cannot modify the elements of the array.
The second parameter, size
, represents the number of elements in the array.
Inside the function, a variable sum
is initialized to 0
and is used to accumulate the sum of the array elements. A for
loop iterates through the array, adding each element to sum
. Once the loop completes, the function returns the calculated sum to the caller.