xdot
xdot

Reputation: 148

C++ array as function parameter

using Data = char[10];
void f(Data x)
{
    x = nullptr; // this compiles
}
void g(Data &x)
{
    x = nullptr; // this does not compile, msvc complain "expression must be a modifiable lvalue
}

I am confused why the assignment expression in f compiles, but does not compile in g. I expect that both assignment will fail since array type is not modifiable.

Any reference to c++ standard will be appreciated.

Upvotes: 0

Views: 51

Answers (1)

This has everything to do with function parameter type adjustment ([dcl.fct]/5):

After determining the type of each parameter, any parameter of type “array of T” or of function type T is adjusted to be “pointer to T”.

Since a type alias is equivalent to the type it names, in the first case the type is determined as char[10] and adjusted to char*. You can modify a pointer.

In the second case, you form a char(&)[10]. It's a reference to an array, and arrays cannot be assigned to, even via a reference.

Upvotes: 2

Related Questions