Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why share the use of the ampersand (&) for both address operator and the reference declarator? [closed]

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?

like image 698
learnvst Avatar asked May 30 '12 12:05

learnvst


1 Answers

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.

like image 66
Luchian Grigore Avatar answered Sep 30 '22 17:09

Luchian Grigore