C++ References
In C++, a reference is an alias or alternative name for an already existing variable. References provide a way to access the same memory location of a variable using different names. They are often used for passing arguments to functions, returning values from functions, and creating aliases for variables.
1. Declaring and Using References
Example of declaring and using a reference:
#include <iostream>
int main() {
// Declare a variable
int num = 10;
// Declare a reference to num
int &refNum = num;
// Output the value of num and refNum
std::cout << "num = " << num << std::endl;
std::cout << "refNum = " << refNum << std::endl;
// Modify the value through the reference
refNum = 20;
// Output the modified value of num and refNum
std::cout << "Modified num = " << num << std::endl;
std::cout << "Modified refNum = " << refNum << std::endl;
return 0;
}
2. Passing References to Functions
Example of passing references to functions:
#include <iostream>
// Function to swap two integers using references
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
// Output initial values of x and y
std::cout << "Before swap: x = " << x << ", y = " << y << std::endl;
// Call swap function with references
swap(x, y);
// Output swapped values of x and y
std::cout << "After swap: x = " << x << ", y = " << y << std::endl;
return 0;
}
3. Returning References from Functions
Example of returning references from functions:
#include <iostream>
// Function to return a reference to an integer
int &findMax(int &a, int &b) {
return (a > b) ? a : b;
}
int main() {
int num1 = 100, num2 = 200;
// Call findMax function and assign its reference to maxNum
int &maxNum = findMax(num1, num2);
// Output the maximum value using the reference
std::cout << "Max number: " << maxNum << std::endl;
// Modify the value through the reference
maxNum = 300;
// Output the modified value of num2
std::cout << "Modified num2: " << num2 << std::endl;
return 0;
}
Conclusion
References in C++ provide an alias to an existing variable, allowing you to manipulate data through different names and enhancing code clarity and efficiency. This chapter covered basic reference declaration, usage scenarios such as passing references to functions and returning references from functions. Understanding references enables you to leverage them effectively in C++ programming for tasks like function parameter passing and managing shared data.