Skip to content

Pass By Reference

#include <iostream>
using namespace std;

// Defining a method which calculates the square of a given number
// Pass by Value: The value of num1 is copied into the parameter of getSquare1
int getSquare1(int num1) {
    return num1 * num1;
}

// Pass by Reference: The reference (or address) of num2 is passed to getSquare2
// Any changes made to num2 in this method will reflect in the original variable
int getSquare2(int &num2) {
    num2 = num2 * num2;
    return num2;
}

int main(int argc, char *argv[]) {
    int num1 = 2, num2 = 2;

    // Using getSquare1 - Pass by Value
    // The original num1 is not changed after this call
    cout << "Square of num1 (by value): " << getSquare1(num1) << endl;
    cout << "Value of num1 after getSquare1: " << num1 << endl;

    // Using getSquare2 - Pass by Reference
    // The original num2 is changed after this call
    cout << "Square of num2 (by reference): " << getSquare2(num2) << endl;
    cout << "Value of num2 after getSquare2: " << num2 << endl;

    return 0;
}

Stay updated!

Receive insights on tech, leadership, and growth.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.