Reputation: 1065
All other declaration syntaxes in C++ make a lot of sense, for examples:
int i;
i
is an int
int *i;
when i
is dereferenced, the result is an int
int i[];
when i
is subscripted, the result is and int
int *i[];
when i
is subscriped, then the result is derefrenced, the final result is an int
But when you look at the syntax for reference variables, this otherwise consistent reasoning falls apart.
int &i = x;
“when the address of i
is taken, the result is an int
” makes no sense.
Am I missing something, or is this truly an exception to the apparent reasoning behind the other sytaxes? If it is an exception, why was this syntax chosen?
Edit:
This question addresses why the &
symbol may have been chosen for this purpose, but not whether or not there is a universally consistent way to read declarations different from the way described above.
Upvotes: 1
Views: 167
Reputation: 119164
Once bound, a reference becomes an alias for its referent, and cannot be distinguished from it (except by decltype
). Since int&
is used exactly as int
is, a declaration-follows-usage syntax could not work for declaring references.
The syntax for declaring references is pretty straightforward, still. Just write down a declaration for the corresponding pointer type, then replace the *
used for the initial dereference by &
or &&
.
Upvotes: 5