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?*/);
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With