Introduction
References let us use another name for a variable. This helps us change the original data without copying it.
References let us use another name for a variable. This helps us change the original data without copying it.
type &referenceName = variableName;
The & symbol means this is a reference.
Once set, a reference cannot be changed to refer to another variable.
ref is a reference to x. Changing ref changes x.int x = 10; int &ref = x;
void addOne(int &num) { num = num + 1; }
r changes a because r is a reference to a.int a = 5; int &r = a; r = 20; // Now a is 20
This program shows how a reference lets the function increase change the original variable number.
#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; }
References must be initialized when declared.
References cannot be null or uninitialized like pointers.
Using references can make your code faster by avoiding copies.
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.
num?int &ref.void addOne(int &x) {
x = x + 1;
}
int main() {
int a = 5;
addOne(a);
std::cout << a;
return 0;
}addOne takes x as a reference, so it modifies the original variable.a is 5, addOne(a) adds 1, so a becomes 6. Then it prints 6.void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 10, y = 20;
swap(x, y);
std::cout << x << " " << y;
return 0;
}Pass the test and this pattern moves unknown