I would like to be able to pass a const array argument to a method in C++.
I know that when you pass an array to method it is the same than passing a pointer to the
Not sure if it's what you asked about, but maybe it's what you were looking for
void func (const int array[10])
{
//array[0] = 12345; // this wouldn't compile, so 'const' works
}
int main ()
{
int array[10];
func(array);
}
You can use a template taking the array size: http://ideone.com/0Qhra
template <size_t N>
void myMethod ( const int (& intArray) [N] )
{
std::cout << "Array of " << N << " ints\n";
return;
}
EDIT: A possible way to avoid code bloat would be to have a function that takes a pointer and a size that does the actual work:
void myMethodImpl ( const int * intArray, size_t n );
and a trivial template that calls it, that will easily be inlined.
template <size_t N>
void myMethod ( const int (& intArray) [N] )
{ myMethodImpl ( intArray, N ); }
Of course, you'ld have to find a way to test that this is always inlined away, but you do get the safety and ease of use. Even in the cases it is not, you get the benefits for relatively small cost.
If you need the size of the array:
template < std::size_t Size >
void myMethod( const int ( &inTab )[ Size ] );
Per 3.9.3:2
Any cv-qualifiers applied to an array type affect the array element type, not the array type (8.3.4).
and 8.3.4:1
Any type of the form “cv-qualifier-seq array of N T” is adjusted to “array of N cv-qualifier-seq T”, and similarly for “array of unknown bound of T”.
Also, per 8.3.5:5
After determining the type of each parameter, any parameter of type “array of T” or “function returning T” is adjusted to be “pointer to T” or “pointer to function returning T,” respectively.
That means that within a function taking an array parameter, the parameter type is actually a pointer, and because of 3.9.3:2 the pointer is non-cv-qualified:
void foo(const int parameter[10]) {
parameter = nullptr; // this compiles!
}
This does not affect the type of the function itself, because of another clause in 8.3.5:5
After producing the list of parameter types, any top-level cv-qualifiers modifying a parameter type are deleted when forming the function type.
Thus if you want to be able to pass an array with cv qualifiers, it must be by reference:
void foo(const int (¶meter)[10]);