Razzupaltuff
Razzupaltuff

Reputation: 2311

Use initializer list as default value for function/method parameter

I want to do something like

void A (int a[2] = {0,0}) {}

but I get

<source>(1): error C2440: 'default argument': cannot convert from 'initializer list' to 'int []'
<source>(1): note: The initializer contains too many elements

(MSVC v19 x64 latest, doesn't work with gcc x86-64 11.2 either)

Again, I cannot figure what the c++ powers to be fancied as the proper syntax here.

Upvotes: 0

Views: 267

Answers (2)

Sergey Kolesnik
Sergey Kolesnik

Reputation: 3678

Also, you can pass a raw array by const reference:

void A(const int (&arr)[2] = {2, 2})
{}

Upvotes: 0

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123440

The reason this does not work is that this

void A (int a[2]) {}

is just short hand notation for

void A (int* a) {}

You cannot pass arrays by value to functions. They do decay to pointers to the first element. If you use a std::array<int,2> you can easily provide a default argument:

void foo(std::array<int,2> x = {2,2}) {}

Upvotes: 3

Related Questions