It's pretty common knowledge that the semantically accurate way to declare pointers is
int *x;
instead of
int* x;
This is because C sees *x
as an int, not x
as an int pointer.
This can be easily demonstrated by
int* a, b;
where a
is an int pointer, while b
is an int.
There are at least 5 duplicate questions on Stack Overflow that discuss this issue for pointers. But what about references?
Bjarne Stroustrup says:
A
typical C programmer
writesint *p
; and explains it*p is what is the int
emphasizing syntax, and may point to the C (and C++) declaration grammar to argue for the correctness of the style. Indeed, the * binds to the name p in the grammar.A
typical C++ programmer
writesint* p;
and explains itp is a pointer to an int
emphasizing type. Indeed the type of p is int*. I clearly prefer that emphasis and see it as important for using the more advanced parts of C++ well.
When declaring a pointer variable or argument, you may place the asterisk (or ampersand) adjacent to either the type or to the variable name.
The most important thing is to do this consistently within a single file.
// These are fine, space preceding.
char *c;
const int &i;
// These are fine, space following.
char* c;
const int& i;
While researching for this question, I already found the answer:
The &
needs to be written just like the *
.
The demonstration code is similar to the pointer demonstration code:
int main() {
int a = 0;
int b = 1;
int& ar = a, br = b;
br = 2;
return b;
}
This returns 1, which means that ar
is an int reference, while br
is just an integer.
Thanks to "template typedefs", you can declare multiple references in an (arguably) nicer way:
template<typename T> using ref = T&;
int a, b;
ref<int> ar = a, br = b;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With