0

I am a beginner in c++. I have faced a problem. When I provide an array into a function like this:

void foo(const int a[2])
{
    // some code...
}

int main() {
    foo({ 23, 63 });

    return 0;
}

I get errors:

E0146 Too many initializers

C2664 "void foo(const int [])": cannot convert argument 1 from "initializer list" to "const int []"

But when I write that array into a variable and provide the variable into the function, it works okay

const int a[2] = { 23, 63 };
foo(a); // no problem
PHP Master
  • 116
  • 5

2 Answers2

1

In C++, function parameters are never arrays. When you write a parameter with array type, that parameter is adjusted to be a pointer to an element of such array.

So, the parameter of your function is a pointer. Unlike an array, a pointer cannot be initialised using an braced init list of multiple values. This is why your first example doesn't work.

By contrast, a pointer (of appropriate type) can be initialised using an array, because the array implicitly converts to a pointer to first element of the array. This conversion is called "decaying". This is why your second example works.

These two rules of parameter adjustment and array decay complement each other to make it seem like you're passing an array as an argument, without limiting the parameter type to a single array length and without making a copy of the argument (which may be expensive for a long array) which is what would be expected in case of non-array object parameter.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

When you use {23, 63} as the argument, it is not an array. But a C++ compiler will be able to initialize a std::initializer_list with it. see the example

#include <iostream>
#include <initializer_list>

void foo(const std::initializer_list<int>& a)
{
  // some code...
}

//array overload
void foo(int(&a)[2])
{
}

//template version examples
template<typename T>
void foo(const std::initializer_list<T>& a)
{
}

template<typename T, size_t _Size>
void foo(T(&a)[_Size])
{
}

int main() 
{
   //here a temporary std::initializer_list instance will be created.
   foo({ 23, 63 });

   int a[] = { 23, 63 };
   foo(a);

   return 0;
}
Nitheesh George
  • 1,357
  • 10
  • 13