Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an array an optional parameter for a c++ function

Tags:

c++

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?*/);
like image 238
Donald Duck Avatar asked Jun 11 '16 07:06

Donald Duck


2 Answers

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.

like image 109
πάντα ῥεῖ Avatar answered Sep 17 '22 08:09

πάντα ῥεῖ


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;
}
like image 22
ajneu Avatar answered Sep 21 '22 08:09

ajneu