0

Sorry if this is a duplicate in advance.

I am trying to return an array of booleans in a function in c++, where the array's size is declared as an argument to the array.

Could I do something like this?

bool returnBools(int size) {
    bool returnValue[size];

    // Do some stuff with array

    return returnValue;
}
realhuman
  • 137
  • 1
  • 8
  • It's not possible to return an array from a function in C++. use a `std::vector` instead. – john Nov 30 '22 at 09:17
  • Yes, when you use an `std::vector` instead of a C style array. – mch Nov 30 '22 at 09:17
  • 1
    The declared return type `bool` is a *single* value, not an array. And you can't return a C-style array as it will decay to a pointer (to its first element) and that pointer will become invalid as soon as the function returns. And [C++ doesn't have variable-length arrays](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) anyway. Use `std::vector` instead, both for the "array" as well as for the return type. – Some programmer dude Nov 30 '22 at 09:17

1 Answers1

4

It's not possible to return an array from a function in C++ (nor in C). The C++ solution is to use a vector.

#include <vector>

std::vector<bool> returnBools(int size) {
    std::vector<bool> returnValue(size); // note () not []

    // Do some stuff with vector

    return returnValue;
}

When manipulating the vector you can use the notation you are already familiar with for arrays e.g. returnValue[i] = true; etc. plus a whole lot more.

john
  • 85,011
  • 4
  • 57
  • 81