4 ms·
> I don't find those obfuscatory at all either, and instantly understood them upon first reading I understood the whole list of these obfuscation tricks upon
by jackewiehose 6y ago
> I don't find those obfuscatory at all either, and instantly
understood them upon first reading
I understood the whole list of these obfuscation tricks upon
first reading but its still obfuscation.
Creating an array instead of an if-else-switch like the second
line is fine but for just two elements and in combination with
!!x (and !!x in general) its just nonsense and doesn't help at
all.
I'm all for code-density and avoiding repetition so I too use ?:
whenever I can but not on the left side of an assignment. That's
just an obfuscated if-else-statement. If normal code results in
very long and "branchy" code you can rearrange your code in a
better way.
- gpderetta 6y agoFWIW, !! is a fairly idiomatic way to cast a value to bool.
- jackewiehose 6y agoInts 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.