3 Nov 2017 • C++ tricks: sized array arguments

In C if you write a function void f( char x[ 4 ] ); then the compiler ignores the 4 and treats it as char * x. This has two problems, firstly sizeof( x ) gives you sizeof( char * ) and not 4 * sizeof( char ) (GCC does warn about this), and the compiler doesn't complain if you pass in an array that's too small.

In C++ you can write void f( char ( &x )[ 4 ] ); instead and it works.

A code example:

void f( char x[ 4 ] ) {
	// warning: 'sizeof' on array function parameter 'x' will return size of 'char*'
	printf( "%zu\n", sizeof( x ) ); // prints 8
}

void g( char ( &x )[ 4 ] ) {
	printf( "%zu\n", sizeof( x ) ); // prints 4
}

int main() {
	char char3[ 3 ] = { };
	char char4[ 4 ] = { };
	char * charp = NULL;

	f( char3 ); // fine
	f( char4 );
	f( charp ); // fine

	g( char3 ); // error: invalid initialization of reference of type 'char (&)[4]' from expression of type 'char [3]'
	g( charp );
	g( char4 ); // error: invalid initialization of reference of type 'char (&)[4]' from expression of type 'char*'

	return 0;
}