Search code examples
c++operator-precedence

Why does a reference to a variable behave as an array of size 1 sometimes?


#include <iostream>
using namespace std;

void outputFirst(int x[]) {
    cout << x[0] << endl;
}

int main() {
    int x = 40;

    // works
    outputFirst(&x);

    // works
    int *y = &x;
    cout << y[0] << endl;

    // invalid types ‘int[int]’ for array subscript
    cout << &x[0] << endl;

    return 0;
}

Why can I use a reference to an int as an array when I pass it to a function or assign it to another variable first, but not directly?

I'm using g++-6.3.


Solution

  • Why can I use a reference to an int

    Note that &x doesn't mean reference to x, it means taking the address of x and you'll get a pointer (i.e. int*) from it. So int *y = &x; means taking the address from x, then y[0] means get the 1st element of the array pointed by the pointer (as if it points to the 1st element of the array which contains only one element (i.e. x) ), so at last it returns x itself.

    And about why &x[0] doesn't work, note that operator[] has higher precedence than operator&. Then &x[0] is interpreted as &(x[0]), while x[0] is invalid since x is just an int.

    You should add parentheses to specify the precedence explicitly, e.g.

    cout << (&x)[0] << endl;