C++ Functions


Introduction

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:

  • The purpose and syntax of functions in C++.
  • How to define a function and call it.
  • Types of functions: void functions, returning functions, and functions with parameters.
  • Examples of C++ functions in action.

1. What is a Function in C++?

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:

  • return_type is the data type of the value the function returns. If it doesn't return anything, it's void.
  • function_name is the name of the function.
  • parameters are the input values passed to the function. These are optional and depend on the function definition.

2. Syntax of a C++ Function

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.
  • The function simply prints a message when called.

3. Functions With Return Values

Functions can return a value, and the return type must match the data type of the returned value.

Example 2: Function Returning a 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:

  • The addNumbers function takes two integer parameters and returns the sum of the two numbers.
  • The return type of the function is int, indicating that it returns an integer.

4. Functions with Parameters

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.

Example 3: Function with Parameters

#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:

  • The function calculateArea takes two double parameters (length and width) and returns the product of these values (i.e., the area of a rectangle).
  • The values 5.0 and 4.0 are passed as arguments to the function during the function call.

5. Function Overloading

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.

Example 4: Function Overloading

#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:

  • Function Overloading allows the same function name calculateArea to be used for both the rectangle and square area calculations, but with different parameters (one for the rectangle, two for the square).
  • The correct function is chosen at compile-time based on the arguments passed.

6. Function Scope and Lifetime

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.

Example 5: Local and Global Variables

#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:

  • The variable globalVar is accessible throughout the program, including inside the function displayNumbers.
  • The variable localVar is only accessible within the function displayNumbers.

7. Passing Arguments to Functions

In C++, you can pass arguments to functions in two main ways:

  • By value: A copy of the argument is passed to the function.
  • By reference: The actual argument is passed, and changes made inside the function affect the original variable.

Example 6: Pass by Value and Reference

#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:

  • Pass by value: The variable x is passed to the function passByValue, but it remains unchanged outside the function.
  • Pass by reference: The variable y is passed to the function passByReference, and its value is modified inside the function, reflecting outside the function as well.

8. Recursion in Functions

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).

Example 7: Recursive Function to Calculate Factorial

#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:

  • The factorial function calls itself with a decremented value of n until it reaches the base case (when n == 0).
  • The recursion "unwinds" and calculates the factorial.