C++ References
π C++ References
A reference in C++ is an alias (another name) for an existing variable.
It does not create a new variable, but refers to the same memory location.
1. Declaring a Reference
refis a reference toxBoth share the same memory
2. Reference Example
β‘ Changing r also changes x.
Β 3. Reference vs Normal Variable
4. References in Function Parameters (Very Important)
Without Reference (Call by Value)
β Original value not changed.
With Reference (Call by Reference)
β Original value is changed.
Example:
5. Swap Two Numbers Using References
6. Reference Must Be Initialized
β Invalid:
β Valid:
Β 7. Reference Cannot Be Reassigned
β‘ r still refers to a.
8. const Reference
β Useful for read-only access
β Prevents accidental modification
9. References with Arrays
Β 10. Reference vs Pointer
| Reference | Pointer |
|---|---|
| Cannot be NULL | Can be NULL |
| No reassignment | Can change address |
| Cleaner syntax | More flexible |
| Must be initialized | Optional initialization |
π Summary
Reference = alias of a variable
Must be initialized
Cannot be NULL or reassigned
Used heavily in functions and loops
Safer alternative to pointers in many cases
