C++ Functions
Functions are fundamental building blocks in C++ programming. They allow you to group a set of statements together to perform a specific task. Using functions makes your code more modular, reusable, and easier to maintain.
In this blog post, we will cover:
A function is a block of code that only runs when it is called. You can pass data to a function, and it can return a result. Functions are used to break down a program into smaller, manageable tasks.
Functions are defined with the following structure:
return_type function_name(parameters) {
// Body of the function
// Perform tasks
return value; // If return_type is not void
}
Where:
void
.Here’s the basic syntax for defining a function:
return_type function_name(parameter1, parameter2, ...) {
// Function code
}
Example 1: Simple Function Without Return Value (Void Function)
#include <iostream>
using namespace std;
// Function definition
void printMessage() {
cout << "Hello from the function!" << endl;
}
int main() {
// Function call
printMessage();
return 0;
}
Output:
Hello from the function!
Explanation:
printMessage
is a function that doesn't return any value, hence it is defined with the void
return type.Functions can return a value, and the return type must match the data type of the returned value.
#include <iostream>
using namespace std;
// Function that returns the sum of two numbers
int addNumbers(int a, int b) {
return a + b;
}
int main() {
int result = addNumbers(5, 3); // Function call
cout << "The sum is: " << result << endl;
return 0;
}
Output:
The sum is: 8
Explanation:
addNumbers
function takes two integer parameters and returns the sum of the two numbers.int
, indicating that it returns an integer.Functions can accept parameters, allowing you to pass data into the function. These parameters are used within the function to perform tasks based on the values passed.
#include <iostream>
using namespace std;
// Function that calculates the area of a rectangle
double calculateArea(double length, double width) {
return length * width;
}
int main() {
double area = calculateArea(5.0, 4.0); // Function call with parameters
cout << "Area of rectangle: " << area << endl;
return 0;
}
Output:
Area of rectangle: 20
Explanation:
calculateArea
takes two double
parameters (length
and width
) and returns the product of these values (i.e., the area of a rectangle).5.0
and 4.0
are passed as arguments to the function during the function call.In C++, you can define multiple functions with the same name but with different parameters. This is known as function overloading. The function is chosen based on the number or type of arguments passed during the call.
#include <iostream>
using namespace std;
// Overloaded function to calculate area of a rectangle (two parameters)
double calculateArea(double length, double width) {
return length * width;
}
// Overloaded function to calculate area of a square (one parameter)
double calculateArea(double side) {
return side * side;
}
int main() {
double rectArea = calculateArea(5.0, 4.0); // Function call with two parameters
double squareArea = calculateArea(5.0); // Function call with one parameter
cout << "Rectangle area: " << rectArea << endl;
cout << "Square area: " << squareArea << endl;
return 0;
}
Output:
Rectangle area: 20
Square area: 25
Explanation:
calculateArea
to be used for both the rectangle and square area calculations, but with different parameters (one for the rectangle, two for the square).Variables declared inside a function are said to have local scope and are destroyed once the function finishes executing. These variables can’t be accessed outside the function. However, variables declared outside all functions (in the main()
function or globally) have global scope.
#include <iostream>
using namespace std;
int globalVar = 10; // Global variable
void displayNumbers() {
int localVar = 20; // Local variable
cout << "Local variable: " << localVar << endl;
cout << "Global variable: " << globalVar << endl;
}
int main() {
displayNumbers(); // Function call
return 0;
}
Output:
Local variable: 20
Global variable: 10
Explanation:
globalVar
is accessible throughout the program, including inside the function displayNumbers
.localVar
is only accessible within the function displayNumbers
.In C++, you can pass arguments to functions in two main ways:
#include <iostream>
using namespace std;
// Pass by value
void passByValue(int a) {
a = a * 2;
cout << "Value inside function (by value): " << a << endl;
}
// Pass by reference
void passByReference(int &b) {
b = b * 2;
cout << "Value inside function (by reference): " << b << endl;
}
int main() {
int x = 5, y = 10;
passByValue(x); // Pass by value (x remains unchanged)
passByReference(y); // Pass by reference (y is modified)
cout << "Original value of x: " << x << endl;
cout << "Original value of y: " << y << endl;
return 0;
}
Output:
Value inside function (by value): 10
Value inside function (by reference): 20
Original value of x: 5
Original value of y: 20
Explanation:
x
is passed to the function passByValue
, but it remains unchanged outside the function.y
is passed to the function passByReference
, and its value is modified inside the function, reflecting outside the function as well.A function in C++ can call itself, and this is known as recursion. Recursive functions are useful for problems that can be broken down into smaller subproblems (e.g., calculating factorials, Fibonacci series).
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 0) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive call
}
}
int main() {
int num = 5;
cout << "Factorial of " << num << " is " << factorial(num) << endl;
return 0;
}
Output:
Factorial of 5 is 120
Explanation:
factorial
function calls itself with a decremented value of n
until it reaches the base case (when n == 0
).