In C , what is the best and simplest way to check if all values in a bool table are true? I tried something like this but it doesn't work
for(i = 0; i < value; i++){
if(bool_table[i] == 0)
table_true = 0;
else
table_true = 1;
}
The problem with this code is that sometimes if the first value is true then it will set table_true = 1
Something like this should do the trick:
table_true = 1;
for(i = 0; i < value; i++)
if (!bool_table[i]) {
table_true = 0;
break;
}
If the following loop goes through the entire array without finding a false
entry, then at the end of the loop i
will equal value
for(i = 0; i < value; i++)
if ( !bool_table[i] )
break;
table_true = (i == value);
I'm not sure how one evaluates "best" or "simplest." Does "best" mean fastest? Or least lines of code? And simplest, is that most simple for a beginner? Or for a group of developers that eat and sleep C and use pointers regularly?
Here's my somewhat unconventional approach:
bool *each = bool_table; // pointer to first element
bool *end = each + value; // stop condition
while (*each && each != end) {
each++;
}
return each != end;
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.