4 ms·
Brain teaser: what does this switch statement print?
A nefarious programming bug awaiting all C programmers...especially when coding on low sleep!
- cypherpunks01 13y agoIs this supposed to reveal something insightful about switch statements in C?
- theonewolf 13y agoThat you can compile with with labels instead of _any_ actual case statements :-) although your source, at a cursory glance, looks like it has valid cases defined.
- bichiliad 13y agoDon't you need to say "case" before every case statement?
- theonewolf 13y agoPrecisely the issue, very easy to miss, still compiles, looks normal.
- _ZeD_ 13y ago$ echo $CFLAGS -Werror -Wall -Wextra -Wold-style-definition -Wmissing-declarations -Wredundant-decls -Wmissing-noreturn -Wshadow -Wpointer-arith -Wcast-align -Wwrite-strings -Winline -Wformat-nonliteral -Wformat-security -Wswitch-enum -Wswitch-default -Winit-self -Wmissing-include-dirs -Wundef -Waggregate-return -Wmissing-format-attribute -Wnested-externs -std=c11 -pedantic
- theonewolf 13y agoNice safer CFLAGS :-) But yeah, that's why this is a "brain teaser" rather than a "compiler teaser." It's not that it _can't_ be caught with a compiler, just that it's easy to miss and acceptable to compilers with default flags.
- Denzel 13y agoNot really a brain teaser: the only case being the default, and the rest simply being labels, makes for a very straightforward program.
- theonewolf 13y agoRight, the point being that you can compile an "almost correct"-looking switch statement with labels instead of actual case statements.
- matthavener 13y agoEvery time I forget to type "case " I'm instantly corrected when my editor (rightly) removes all indentation and puts the label on the leftmost column.
- theonewolf 13y agovim? My editor does this too thank God :-)
- niggler 13y agoNo discussion of C switch statements is complete without a reference to Duff's device: https://en.wikipedia.org/wiki/Duffs_device https://en.wikipedia.org/wiki/Duffs_device
- theonewolf 13y agoYou had me at: "interlacing the structures of a switch and a loop"
- bitbckt 13y ago-Wswitch-enum
- _ZeD_ 13y ago-Werror=switch-enum -Werror=unused-label (but you get the point :D)
- theonewolf 13y agothat's why it's a "Brain teaser" and not a "compiler teaser." If you were inspecting code without a compiler it's easier to miss. The standard '-Wall -Werror' catches it (arguably, it'd be nice if everyone _at least_ did -Wall by default).
- nikbackm 13y agoHow obvious! And yet I missed it :(