0
0
C++programming~5 mins

Why references are needed in C++

Choose your learning style9 modes available
Introduction

References let us use another name for a variable. This helps us change the original data without copying it.

When you want to change a variable inside a function and keep the change outside.
When you want to avoid copying large data like big arrays or objects to save memory.
When you want to make code easier to read by using simpler names for variables.
When you want to pass variables to functions quickly without making copies.
When you want to return multiple values from a function by changing variables passed in.
Syntax
C++
type &referenceName = variableName;

The & symbol means this is a reference.

Once set, a reference cannot be changed to refer to another variable.

Examples
Here, ref is a reference to x. Changing ref changes x.
C++
int x = 10;
int &ref = x;
This function uses a reference to change the original variable passed in.
C++
void addOne(int &num) {
    num = num + 1;
}
Assigning to r changes a because r is a reference to a.
C++
int a = 5;
int &r = a;
r = 20;
// Now a is 20
Sample Program

This program shows how a reference lets the function increase change the original variable number.

C++
#include <iostream>

void increase(int &value) {
    value = value + 5;
}

int main() {
    int number = 10;
    std::cout << "Before: " << number << "\n";
    increase(number);
    std::cout << "After: " << number << "\n";
    return 0;
}
OutputSuccess
Important Notes

References must be initialized when declared.

References cannot be null or uninitialized like pointers.

Using references can make your code faster by avoiding copies.

Summary

References let you use another name for the same variable.

They help change original data inside functions without copying.

References make code simpler and more efficient.