Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the semantically accurate position for the ampersand in C++ references

Tags:

c++

reference

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?

like image 871
mic_e Avatar asked Mar 31 '14 16:03

mic_e


3 Answers

Bjarne Stroustrup says:

A typical C programmer writes int *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 writes int* p; and explains it p 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;
like image 127
Alejandro Blasco Avatar answered Nov 05 '22 13:11

Alejandro Blasco


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.

like image 25
mic_e Avatar answered Nov 05 '22 11:11

mic_e


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;
like image 8
fredoverflow Avatar answered Nov 05 '22 12:11

fredoverflow