Make an array an optional parameter for a c++ function
You can use a nullptr
or a pointer to a global const array to denote the default value:
void myFunction(int myArray[] = nullptr ) {
// ^^^^^^^
}
This is because int myArray[]
is type adjusted to a int*
pointer when used as function parameter.
The default argument must have static linkage (e.g. be a global). Here's an example:
#include <iostream>
int array[] = {100, 1, 2, 3};
void myFunction(int myArray[] = array)
{
std::cout << "First value of array is: " << myArray[0] << std::endl;
// Note that you cannot determine the length of myArray!
}
int main()
{
myFunction();
return 0;
}
If the default array is small enough (note: it can be smaller than the size of the actual array type), so that copying it is not an issue, then (since C++11) std::array
is probably the most expressive, "C++-ish" style (as Ed Heal hinted in a comment). Apart from the copy-init burden on each argument-less f()
call, using the default, the array itself has the same performance properties as built-in C-like arrays, but it doesn't need an awkward, separately defined default variable:
#include <array>
// Just for convenience:
typedef std::array<int, 3> my_array;
void f(const my_array& a = {1, 2, 3});
(NOTE: passing by const ref. avoids the copy at least for those cases, where you do pass an argument explicitly.)