Thuta Learning
IntermediateProgrammingbeginner

References

Relax. We'll talk through this in plain words — no textbook voice.

A reference is just another name for a variable that already exists. It's useful when you want to work with the original value directly instead of making a copy. Using a reference as a function parameter lets you modify the original without copying the value.

cpp
#include <iostream>
#include <string>
using namespace std;

void renameCourse(string &courseName) {
    courseName = "Advanced C++";
}

int main() {
    string course = "Basic C++";
    string &alias = course;

    cout << alias << endl;
    renameCourse(course);
    cout << course;
    return 0;
}

alias is a reference to course, so it points to the exact same value. renameCourse(string &courseName) uses a reference parameter, so any change made inside the function affects the original variable.

You should see
Basic C++ Advanced C++

Info

A reference has to be initialized the moment you declare it — no exceptions. Unlike a pointer, you can't point it at a different address later on.

Easy traps

  • If you don't want the original value to change, use a const reference like const string &name. That keeps things safe without copying anything.
References | Thuta Learning