Sir Visto
Sir Visto

Reputation: 703

Address of array prvalue

I don't understand why this doesn't work:

auto a = (int[]){1, 2, 3, 4, 5};

> error: taking address of temporary array

I understand that array lvalues decay to pointers when converted to rvalues but here the array is already an rvalue (actually a prvalue) so no decay should be needed. I would have expected a to be deduced and initialized to int[5]. Why is it trying to take the address of a temporary?

Upvotes: 4

Views: 282

Answers (1)

Guillaume Racicot
Guillaume Racicot

Reputation: 41780

I would have expected a to be deduced and initialized to int[5]

Sadly, this is not how C arrays work. Arrays decays into pointers. You cannot really have an "array value". If you replace auto by the deduced type, it looks like this:

int* a = (int[]){1, 2, 3, 4, 5};

The decay must take the address to make the pointer.

This is easily fixed by using references, since reference to temporaries extends their lifetime:

auto&& a = (int[]){1, 2, 3, 4, 5}; // works!

Here's the example running on compiler explorer.

Of course, with std::array you get a nice syntax and value semantics:

auto a = std::array{1, 2, 3, 4, 5};

Upvotes: 5

Related Questions