Make array an optional parameter for C ++ function

In C ++, you can make an optional parameter as follows:

void myFunction(int myVar = 0); 

How do you do this with an array?

 void myFunction(int myArray[] = /*What do I put here?*/); 
+5
source share
2 answers

The default argument must have a static binding (e.g. global). Here is 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; } 
+3
source

You can use nullptr or a pointer to the const global array to indicate the default value:

 void myFunction(int myArray[] = nullptr ) { // ^^^^^^^ } 

This is because int myArray[] has a type adjusted to an int* pointer when used as a function parameter.

+9
source

All Articles