ProAnswers.org

What is a reference in c++?

1 Like

A reference is an alias (an alternate name) for an object. It is frequently used for pass-by-reference.

References are frequently used for pass-by-reference:

void swap(int& i, int& j)
{
int tmp = i;
i = j;
j = tmp;
}

int main()
{
int x, y;

swap(x,y);

}

Here i and j are aliases for main’s x and y respectively. In other words, i is x — not a pointer to x, nor a copy of x, but x itself. Anything you do to i gets done to x, and vice versa.