Question

In C++, the ampersand character (&) can be used to get the address of an lvalue, a function designator, or a qualified name . .

int y;
int* p_to_y = &y;

The character has a shared use in C++ as a reference declarator . .

int y;
int& y_alias = y;

When learning C++ after having a cursory knowledge of C, this double usage caused me a lot of confusion! I understand that the context in which the symbol is used makes all the difference, but given that references and pointers are important concepts that should not be confused, can anyone suggest why the & was recycled rather than using a new alternative symbol?

Was it helpful?

Solution

First, don't worry, you'll get over this confusion soon enough.

There can be multiple reasons:

  • logically, they are somehow connected. A reference behaves like a pointer, which is the address of an object.

  • Not a lot of free symbols. Looking at my top row of the keyboard, I can only see... well, only $ and @. I personally wouldn't like either, but that's maybe just because I got used to &.

  • The counter-reason you provided can be regarded as a pro-reason - as to not add another symbol to the language. Think about it - most symbols available in C++ are also available in C. The intention could have been for a smooth learning curve from people migrating from C. And since & is logically connected to the concept of reference, it's the most suited.

OTHER TIPS

can anyone suggest why the & was recycled

Because &y and int& both are "about addresses" in some way: one creates a pointer, which is a thin abstraction of a memory address, and the other indicates a reference, which is like a pointer that can never be null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top