Home > Blogs > 30 C++ Tips in 30 Days: Tip # 21 using references to arrays

30 C++ Tips in 30 Days: Tip # 21 using references to arrays

By  Dec 9, 2007

Topics: Programming, C/C++

C++ allows you to declare a reference to an array. Such a reference encodes the array's dimension as part of its type so you can use reference to arrays to enforce compile-time bounds checking.

Because operator & takes lower precedence than [], you need to parenthesize the ampersand in a reference-to-array declaration. For example, the following function takes a reference to an array of 20 ints called arr:

void func( int (&arr) [20]); 

If you pass an array with the wrong size or type to func() you'll get a compilation error:

int x[21];
func(x); //cannot convert 'int [21]' to 'int (&)[20]'
int y[20];
func(y); //OK

You can use references to arrays with templates too:

template <typename T> void func( T(&arr)[20]);
int y[20];
double d[20];
double f[21];
func(y); //OK, generating func<int>
func (d); //OK, generating func<double>
func (f); //error

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.

Other Things You Might Like

Xamarin Unleashed

Xamarin Unleashed