11

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?*/);
4
  • You could do something like int myArrayDefault[] = {1,2,3}; void myFunction(int * myArray = myArrayDefault); Commented Jun 11, 2016 at 7:45
  • Note that the definition is no different than void myFunction(int *myArray). You are not passing an array. Commented Jun 11, 2016 at 7:45
  • In C++, an array can't really be a parameter. You can have a pointer to element, reference to array, or pointer to array. But not an array. Commented Jun 11, 2016 at 7:46
  • 3
    Why not use std::array or std::vector? Commented Jun 11, 2016 at 7:46

4 Answers 4

13

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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;
}

Comments

1

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.)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.