0
0
C++programming~5 mins

Reference declaration in C++

Choose your learning style9 modes available
Introduction

A reference lets you create a new name for an existing variable. It helps you work with the same data without copying it.

When you want to change a variable inside a function without copying it.
When you want to avoid copying large data like big arrays or objects.
When you want to make your code easier to read by using a simpler name for a variable.
When you want to pass variables to functions efficiently.
When you want to return a variable from a function without copying it.
Syntax
C++
type &referenceName = existingVariable;

The ampersand (&) symbol means you are creating a reference.

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

Examples
Creates a reference ref to the variable x.
C++
int x = 10;
int &ref = x;
alias is another name for value.
C++
double value = 3.14;
double &alias = value;
Changing r changes a because they are the same variable.
C++
int a = 5;
int &r = a;
r = 10; // changes a to 10
Sample Program

This program shows how changing the reference ref changes the original variable original.

C++
#include <iostream>

int main() {
    int original = 20;
    int &ref = original; // reference declaration

    std::cout << "Original before change: " << original << "\n";
    ref = 50; // change through reference
    std::cout << "Original after change: " << original << "\n";

    return 0;
}
OutputSuccess
Important Notes

References must be initialized when declared.

References cannot be null or uninitialized.

References are safer and easier to use than pointers for many cases.

Summary

A reference is an alias for another variable.

Use references to avoid copying and to modify variables directly.

References must be initialized and cannot be changed to refer to another variable.