0
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.

xdot
  • 128
  • 8
  • 1
    Possible duplicate of [When a function has a specific-size array parameter, why is it replaced with a pointer?](https://stackoverflow.com/questions/1328223/when-a-function-has-a-specific-size-array-parameter-why-is-it-replaced-with-a-p) – user7860670 Nov 20 '17 at 07:26
  • Prefer using a `std::array` or `std::vector` instead. – Jesper Juhl Nov 20 '17 at 07:30

1 Answers1

2

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.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • So the standard acts different between type is "array of T" and type is "reference to array of T", I might just accept that although it seems weird to me... – xdot Nov 20 '17 at 07:55
  • @xdot - That array type pulled in from C *are* weird. I concur with the comment on your post. `std::array` is better for such things. It's an actual value type. – StoryTeller - Unslander Monica Nov 20 '17 at 07:56