C/C++ Arena

References in C++

What a C++ reference is, pass by reference vs pass by value, const references, and references vs pointers.

A reference is another name for an existing object: int &r = x; means using r is using x. Unlike a pointer, a reference must be bound when it's created, can't be null, and can't be re-pointed.

References shine as parameters:

Never return a reference to a local variable: the local is destroyed when the function returns.

Example

#include <iostream>
#include <string>

void shout(std::string &s) { s += "!"; }
std::size_t len(const std::string &s) { return s.size(); }

int main() {
    std::string msg = "hello";
    shout(msg);
    std::cout << msg << " " << len(msg) << "\n";
    return 0;
}

Output:

hello! 6

Watch it run: References are another name

Practice it