Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In regards to array size calculation [duplicate]

Tags:

c++

Possible Duplicate:
Can someone explain this template code that gives me the size of an array?

Hi, I am looking at the answer posted here:

Computing length of array

Copied here:

template <typename T, std::size_t N>
std::size_t size(T (&)[N])
{
    return N;
}

Can some one pls explain me the significance of (&) ?

like image 656
Kiran Avatar asked Feb 12 '26 11:02

Kiran


2 Answers

The & says the array is passed by reference. That prevents the type from decaying to pointer. Without passing by reference you would get that decay, and no information about the array size.

Non-template example:

void foo( int (&a)[5] )
{
    // whatever
}

int main()
{
    int x[5];
    int y[6];

    foo( x );           // ok
    //foo( y );         // !incompatible type
}

Cheers & hth.,

like image 78
Cheers and hth. - Alf Avatar answered Feb 15 '26 02:02

Cheers and hth. - Alf


The & means that the array is to be passed by reference. Arrays can't be passed by value, because in this case they decay to a pointer to the first item. If that happens, the size information associated with the array type is lost.

It is in parenthesis, because otherwise that would mean the function accepts a pointer to reference. Although such a thing is not legal in C++, the syntax is consistent with how you declare a pointer to array.

int (*arr)[3]; // pointer to array of 3 ints
int* p_arr[3]; // array of pointers

int (&arr)[3]; // reference of array of 3 ints
int& r_arr[3]; //array of references (not legal in C++)
like image 29
UncleBens Avatar answered Feb 15 '26 02:02

UncleBens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!