EZ

Eduzan

Learning Hub

Eduzan
Eduzan / C++

C++ Functions

A function is a set of statements designed to perform a specific task and is executed only when called. Functions allow you to modularize code, reducing redundancy and improving clarity. By encapsulating common tasks within functions, we avoid repeating the same logic multiple times, making the code more manageable and easier to maintain.

Syntax:

void function(int size)
{
    int array[size];
    // code to manipulate the array
}

Example:

// C++ Program to demonstrate the working of a function
#include <iostream>
using namespace std;

// Function that takes two integers as parameters
// and returns the larger of the two
int max(int x, int y) {
    return (x > y) ? x : y;
}

int main() {
    int a = 15, b = 25;

    // Calling the max function
    int result = max(a, b);

    cout << "The maximum value is " << result;
    return 0;
}

Output:

The maximum value is 25

Why Do We Need Functions?

  • Code Reusability: Avoid redundancy by reusing functions across the program.
  • Modularity: Code becomes more organized and easier to understand when divided into functions.
  • Abstraction: Using functions hides internal details, making complex tasks easier to use through simple function calls.

Function Declaration

A function declaration tells the compiler about the function’s name, parameters, and return type. Here is an example:

// Function declarations
int add(int, int);         // Function with two integer parameters
float subtract(float, int); // Function with float and int parameters
char* reverseString(char*); // Function that returns a char pointer

Types of Functions

1. User-defined Functions: Functions created by the user to perform specific tasks.
2. Library Functions: Predefined functions in C++ that you can use directly, such as sqrt(), strlen(), etc

Passing Parameters to Functions

There are two common ways to pass parameters to functions:

  • Pass by Value: A copy of the variable is passed. Modifications inside the function do not affect the original variable.
  • Pass by Reference: The function receives the memory address of the variable, and changes made inside the function affect the original variable.

Function Example: Pass by Value

#include <iostream>
using namespace std;

void modify(int x) {
    x = 50;  // Changes won't affect the original variable
}

int main() {
    int num = 10;
    modify(num);
    cout << "Value of num: " << num;  // Outputs 10
    return 0;
}

Function Example: Pass by Reference

#include <iostream>
using namespace std;

void modify(int &x) {
    x = 50;  // Changes will affect the original variable
}

int main() {
    int num = 10;
    modify(num);
    cout << "Value of num: " << num;  // Outputs 50
    return 0;
}

Function Returning a String example: 

#include <iostream>
#include <string>

std::string greet() {
    return "Hello, C++!";
}

int main() {
    std::string message = greet();
    cout << message;
    return 0;
}

Output:

Hello, C++!

Function Returning a Pointer example:

#include <iostream>
using namespace std;

int* createArray(int size) {
    int* arr = new int[size];  // Dynamically allocate memory
    for (int i = 0; i < size; ++i) {
        arr[i] = i * 2;
    }
    return arr;
}

int main() {
    int* arr = createArray(5);
    for (int i = 0; i < 5; ++i) {
        cout << arr[i] << " ";  // Outputs: 0 2 4 6 8
    }
    delete[] arr;  // Free allocated memory
    return 0;
}

Output:

0 2 4 6 8

Callback Function Example:

#include <iostream>
using namespace std;

typedef void (*Callback)();  // Define a callback function type

void action(Callback callback) {
    cout << "Performing action...\n";
    callback();  // Call the passed callback function
}

void myCallback() {
    cout << "Callback function executed!";
}

int main() {
    action(myCallback);
    return 0;
}

Output:

Performing action...
Callback function executed!

Differences Between Call by Value and Call by Reference

C++ Functions
Call by ValueCall by Reference
A copy of the value is passed.The reference (memory address) is passed.
Changes do not affect the original.Changes affect the original.
Actual and formal parameters are stored at different locations.Actual and formal parameters share the same location.
End of lesson.