References in C++
A reference is another name for an existing variable — safer and cleaner than a pointer for passing arguments.
Easy
void scale(double &value, double gain) { value *= gain; }
double v = 2.0;
scale(v, 3.0); // v is now 6.0
void print(const std::string &s); // pass large objects by const reference: no copy
A reference must be initialised, can't be null and can't be re-bound to another variable. Use const T& for read-only parameters, T& when the function must modify the argument.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.