In c++, you can make a parameter optional like this:
void myFunction(int myVar = 0);
How do you do that with an array?
void myFunction(int myArray[] = /*What do I put here?*/);
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.)
Well, in modern C++ 17 you can use std::optional.
std::optional<std::array<int,4>> oa;
// ...
if ( oa )
{
// there is content in oa
*oa // get the content
}
else
{
// there is no content inside oa
}
I used std::array as my representation of the array but you could just as well use raw arrays, vectors, whatever.
int myArrayDefault[] = {1,2,3}; void myFunction(int * myArray = myArrayDefault);void myFunction(int *myArray). You are not passing an array.std::arrayorstd::vector?