

Brain teaser: what does this switch statement print? - theonewolf
https://gist.github.com/theonewolf/5486167
A nefarious programming bug awaiting all C programmers...especially when coding on low sleep!
======
matthavener
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.

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

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

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

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

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

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

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

~~~
_ZeD_

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

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

~~~
theonewolf
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.

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

------
nikbackm
How obvious!

And yet I missed it :(

------
bitbckt
-Wswitch-enum

~~~
_ZeD_
-Werror=switch-enum -Werror=unused-label

(but you get the point :D)

~~~
theonewolf
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).

