6 ms·
Ints are automatically converted to bool, there is no need to cast. What this does is it restricts the int to 1 or 0. The clean way to write this is x ? 1 : 0.
by jackewiehose 6y ago
Ints are automatically converted to bool, there is no need to cast.
What this does is it restricts the int to 1 or 0. The clean way to
write this is x ? 1 : 0. This is understandable even if you don't know
the Boolean inversion of 0 is 1 (Which isn't self-evident. For example
in Basic its -1).
- gpderetta 6y agoThey 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 6y 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 6y agoYou can also typecast to bool since C99. (bool)x if you include <stdbool.h> or (_Bool) if not.
- userbinator 6y 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.