0

I'm writing a function to check if all values of an array are true. If I write

int main(){
bool Janmaat[3]={true, true, true};

int size_arr=sizeof(Janmaat)/sizeof(Janmaat[0]);
bool value=true;
int i;

for(i=0;i<size_arr;i++){
    if(!Janmaat[i]){
        value=false;
    }
}
cout<<value;
return 0;
}

value stays true. If I encapsulate it into a function though

bool all_true(bool arr[]){

int size_arr=sizeof(arr)/sizeof(arr[0]);
bool value=true;
int i;

for(i=0;i<size_arr;i++){
    if(!arr[i]){
        value=false;
    }
}

return value;

}

int main(){

bool Janmaat[3]={true, true, true};

cout<<all_true(Janmaat);
return 0;
}

it returns false. What's going on?

Plinth
  • 289
  • 1
  • 13

1 Answers1

3

When an array is passed to a function expecting a pointer, it automatically decays to a pointer. That means that arrays cannot be passed by value. arr from all_true is a pointer. sizeof(arr) will therefore yield the size of the pointer, not the whole array.

Different ways to handle this:

  1. Pass the size as an argument. Chang the declaration to

    bool all_true(bool arr[], size_t size)
    

    and adjust the code accordingly.

  2. Pass an std::array or a std::vector (std::bitset is technically feasible too). As this is C++, this is surely the better option.


Notes:

  • If one element is false, all_true will definitely return false. To shorten the runtime you could return false; in the if statement immediately.

Y'know Linus Torvalds? The guy who invented Linux and regularly insults Linux kernel "developers" (some deserve the double quotes; some don't)?
This might interest you then. :-)

cadaniluk
  • 15,027
  • 2
  • 39
  • 67