When passing or returning references in C++, there are a few important things to keep in mind:
Here's an example of a bad practice - returning a reference to a local variable:
int& BadFunction() {
int x = 10;
// Error: returning reference to local variable
return x;
}
Instead, you could return by value:
int GoodFunction() {
int x = 10;
return x; // Okay: returning by value
}
Or, if you really need to return a reference, make sure it's to a non-local variable:
int global_x = 10;
int& OkayFunction() {
// Okay: returning reference to global variable
return global_x;
}
But in general, returning by value is safer and often just as efficient due to compiler optimizations.
Answers to questions are automatically generated and may not have been reviewed.
Learn the fundamentals of references, pointers, and the const
keyword in C++ programming.