简体   繁体   中英

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

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM