RE: https://hachyderm.io/@simontatham/117653935395211357
When I say "nobody teaches C properly", I am generally thinking of concepts like ownership, strong pointers vs. weak pointers, storage vs. structure, error reporting conventions, etc. that no programming course mentions.
I am wrong. I should be thinking of much more elementary things that are wrongly taught, such as "never use goto", apparently taken extremely literally by numerous students.
It takes one lesson to learn what's wrong with goto and why, and in what cases its use is acceptable. (You can learn this by experience, but for instance, it is perfectly okay to factorize destructors or error management at the end of a frame with goto; defer may replace that use case soon-ish.)
But if you have been taught "never use goto" and apply it literally without understanding the reason for the rule, you may just come up with that instead.
If you have more than 3 C lessons and 2 hours of practice behind you, and you do that, you should never be allowed near a C compiler again. Nor a text editor, just to be sure.
Reminded of this in conversation recently: possibly the nastiest piece of abuse of the C switch statement rules I know of that _wasn't_ done by either me or Tom Duff. This was contributed to #PuTTY's terminal code in 2000 as part of a much larger patch (and removed again in a 2001 rewrite).
The switch is processing the final character of one of the terminal escape sequences ESC#3, ESC#4, ESC#5, ESC#6 and ESC#8. Four of them do something very similar: they set an attribute on the current terminal line (indicating whether the text is double-width or double-height). The fifth is the odd one out. So you want a switch statement in which four of the five cases share _most_ of their code: each sets the line attribute to a different value, but the code for actually writing it into the terminal is the same.
You could write four case statements sharing a handler, and have a secondary switch inside the handler to choose the attribute. Or you could have four separate handlers that choose an attribute value, then hold your nose and write a 'goto' from each one to the shared code that writes it into the terminal data. Or you could put the shared code in a subroutine a long way away from here, and have four independent case handlers all call it with a different parameter.
Or you could do this, which complies with the letter of 'don't use goto', but makes you wish it hadn't! Control enters at one of the four case statements, and after setting the attribute variable, it then skips over each of the following case labels because of the if (0) { ... }. Then all of them fall through to the shared handler.
yes @dalias that includes you 😝 https://git.musl-libc.org/cgit/musl/tree/src/stdio/vfprintf.c#n597
vfprintf.c\stdio\src - musl - musl - an implementation of the standard library for Linux-based systems