c++default-valuemethod-parameters

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.


Solution

  • 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}) {}