4 ms·
From clang's source code: // switch(bool_expr) {...} is often a programmer error, e.g. // switch(n && mask) { ... } // Doh - should be "n & mask".
by detrino 13y ago
From clang's source code:
// switch(bool_expr) {...} is often a programmer error, e.g.
// switch(n && mask) { ... } // Doh - should be "n & mask".
// One can always use an if statement instead of switch(bool_expr).
I agree that clang should not warn on this without asking for warnings and even then it should be possible to disable it. Maybe it would be a good idea to file a bug report.
That being said, I can't imagine why you would ever choose to switch on a bool, and even go to the trouble to add a cast instead of just writing an if statement.
Also, my clang and g++ with "-Wall -Wextra" does not warn on an empty while statement.
- byuu 13y agoThanks for digging that up. Interesting to see their rationale. Seems like they could extend the test to not warn if it's just switch(var) only, but it might have to happen at a different eval level for that to work. > I can't imagine why you would ever choose to switch on a bool In my case, it's for opcode execution. They consist of various bit fields that control the behavior, some are only 1-bit wide, some are 2-bits to 5-bits wide. The implementation is a series of switch statements, one after the other, that have cases for all possible values. So by using switch() in all cases, the code looks consistent. So this is kind of what I dislike about style choice warnings. It's easy to presume there's no valid use case, until you actually find one later on. I get that people can make mistakes, but when I know for certain that I haven't made a mistake, I don't like having to change my code anyway. Could I force the boolean values to unsigned types even though they're only 1-bit? Yes. Could I just do if/else anyway here? Yes. But I don't want to. I'm happy with my code, and received no warnings at all when I wrote it with GCC several years ago. It's only a "problem" now that I need Clang to target OS X. > Also, my clang and g++ with "-Wall -Wextra" does not warn on an empty while statement Hmm, good to hear. If I get to my dev PC before the post is buried, I'll post the output I was getting.
- cokernel_hacker 13y agoLooks like somebody added -Wswitch-bool just now: http://lists.cs.uiuc.edu/pipermail/cfe-commits/Week-of-Mon-20140310/101098.html http://lists.cs.uiuc.edu/pipermail/cfe-commits/Week-of-Mon-2...
- byuu 13y agoOh wow, I wonder if someone saw this thread, or if that was just a coincidence. Either way, very cool! Thanks for the heads up! I can't use it now obviously, but I can add a diagnostic disable line that'll work in the future.