worldsalt
worldsalt

Reputation: 1

How do I access boolean array from another function? c++

I have a problem. I need to create a code where I can access bool array information from another function, edit the array and then send it back. I need to use a variable as the size of the array.

Global variable is not an option.

I've tried to pass it by a reference and also using structs.

code for example:

void x(bool (&reserved[sizeOfArray)) {
    if (reserved[1] == true) {
          cout << "it's true";

}    

main() {

int sizeOfArray = 6;
bool reserved[sizeOfArray];

x(reserved[sizeOfArray];

edit: the size of the array is determined when the program is already running

Upvotes: 0

Views: 250

Answers (4)

rturrado
rturrado

Reputation: 8054

You can use boost::dynamic_bitset for dynamic vectors of bools. [Demo]

#include <boost/dynamic_bitset.hpp>
#include <iostream>  // cout

void x(const boost::dynamic_bitset<>& reserved) {
    if (reserved[1] == true) {
          std::cout << "it's true\n\n";
    }
    for (int i{0}; i < reserved.size(); ++i)
    {
        std::cout << "Bit " << i << ": " << reserved[i] << "\n";
    }
}

int main() {
    int sizeOfArray = 6;
    boost::dynamic_bitset<> reserved(sizeOfArray, 0b111010);
    x(reserved);
}

Upvotes: 0

Ted Lyngmo
Ted Lyngmo

Reputation: 117178

You could make it a function template, with the array size as a template parameter:

#include <iostream>

template<size_t N>
void x(bool (&reserved)[N]) {

    // make sure that the array size is at least 2 to not get out of
    // bounds access in reserved[1]:

    if constexpr (N >= 2) {    
        if (reserved[1] == true) {
            std::cout << "it's true\n";
        }
    }
}    

int main() {
    constexpr size_t sizeOfArray = 6; // must be a constant expression
    
    bool reserved[sizeOfArray]{false,true}; // rest will be false

    x(reserved);
}

Output:

It's true

Upvotes: 0

vikram
vikram

Reputation: 364

I think the lightweight method would be to use std::span instead.

#include <iostream>
#include <span>

void x(std::span<bool> reserved) {
    reserved[1] = false;
}    

int main() {

    constexpr size_t sizeOfArray = 6;
    bool reserved[sizeOfArray]{false, true};

    x(reserved);

    if (reserved[1] == false) {
        std::cout << "Hello!" << std::endl;
    }
}

Upvotes: 1

molbdnilo
molbdnilo

Reputation: 66371

If the size is only determined at runtime, you essentially have two options:

  1. Use a dynamically-sized container, like std::vector

    void x(std::vector<bool>& reserved)

  2. Use the "C method" of passing a pointer to the array's first element along with the array size
    void x(bool reserved[], size_t size)

The possible third option of having a "sentinel" value last in the array (like C-strings) won't work with bool, since you only have two values to choose from.

Upvotes: 1

Related Questions