Gregory Chen
Gregory Chen

Reputation: 1

Return type of array access

The below compiles:

int main() {
    int v[] = {0,1,2};
    int a = v[0];
    int& b = v[0];
}

How is it possible that array access (bracket notation) returns an int type in one line, but an int reference in another line? What exactly is the return type of array bracket access, then?

I am new to c++, pardon my ignorance.

Upvotes: 0

Views: 47

Answers (2)

Claim Yang
Claim Yang

Reputation: 329

b is a reference to v[0], so their address is the same, that means b is v[0]. But a is an another variable, so a is just equal to v[0], but a is not v[0], their address is not the same.

For your question, if you have some experience in c language, you can easily write expressions like if(&v[0]==&b) printf("b is a reference to int");

or

if(&v[0]!=&a) printf("a is an int");

to judge that.

Upvotes: 1

Shakhar
Shakhar

Reputation: 442

b is an int reference. So, it is an alias to v[0] and thus is an int. a, on the other hand, gets a copy of the value of v[0]. So, if v[0] changes, a doesn't get the new value but b gets the new value.

Suppose after your code, you do something like:

v[0] = 7;
cout << "a: " << a << "\n";
cout << "b: " << b << "\n";

The output will be:

a: 0
b: 7

Upvotes: 0

Related Questions