Hacker News new | comments | show | ask | jobs | submit login
Brain teaser: what does this switch statement print? (github.com)
25 points by theonewolf 1632 days ago | hide | past | web | 18 comments | favorite



Every 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.


vim? My editor does this too thank God :-)


No discussion of C switch statements is complete without a reference to Duff's device: https://en.wikipedia.org/wiki/Duffs_device


You had me at: "interlacing the structures of a switch and a loop"


Not really a brain teaser: the only case being the default, and the rest simply being labels, makes for a very straightforward program.


Right, the point being that you can compile an "almost correct"-looking switch statement with labels instead of actual case statements.


Don't you need to say "case" before every case statement?


Precisely the issue, very easy to miss, still compiles, looks normal.


    $ 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


Nice 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.


Is this supposed to reveal something insightful about switch statements in C?


That 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.


This is why you compile with -Wall and -Werror...


Maybe if you've never written C before...


How obvious!

And yet I missed it :(


-Wswitch-enum


-Werror=switch-enum -Werror=unused-label

(but you get the point :D)


that'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).




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact

Search: