2 ms·
They are converted to bool in bool context. Outside of that you have to force it. int countNonZero = 0; for (int i = 0; i < values.size(); ++i) {
by gpderetta 7y ago
They are converted to bool in bool context. Outside of that you have to force it.
int countNonZero = 0;
for (int i = 0; i < values.size(); ++i) {
countNonZero += !!values[i];
}
Also c++ has explicit operator bool();
edit: not a great example as values[1] >0 would be better.
- jackewiehose 7y agoYou don't have to enforce a conversion from int to bool if you just want a bool. In this example you don't want to increment by 'bool', you want to increment by 1 or 0 (which are ints). So you use !!x to convert to bool and back to int. The reason I'm pointing this out is that often enough I had to work with code where this distinction was unknown to the author and you come across code like if (!!x) which is, again, just nonsense.
- gallier2 7y agoYou can also typecast to bool since C99. (bool)x if you include <stdbool.h> or (_Bool) if not.
- userbinator 7y agoedit: not a great example as values[1] >0 would be better. Only if that's an array of unsigned ints, as otherwise the code would count only positive nonzeros.