Login
You're viewing the fosstodon.org public feed.
  • Nov 21, 2026, 10:23 AM

    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.

    A snippet of C code from a terminal emulator, shown in the Emacs text editor running in a terminal (as it happens, the same one). In the middle of the screen are four consecutive case statements, with a weird set of 'if (0)' statements to their right, so that when read in file order the if statements interleave with the case labels, putting all but the first of them inside the body of an if (0):

                case '3': nlattr = LATTR_TOP;     if(0) {
                case '4': nlattr = LATTR_BOT;   } if(0) {
                case '5': nlattr = LATTR_NORM;  } if(0) {
                case '6': nlattr = LATTR_WIDE;  }

The if (0) labels are highlighted with a red box to indicate that they are alarming!
    💬 57🔄 376⭐ 548

Replies

  • Nov 21, 2026, 10:23 AM

    This code was in PuTTY for less than a year. But in that time it managed to expose a bug in a C compiler.

    It was a small, independently written compiler (none of the huge code bases everyone's heard of now). We had an email from its maintainer to let us know – and to ask us what the code was _meant_ to do, because fair enough, it isn't obvious to everybody at first glance!

    The bug was that the compiler optimised away if (0) { ... } statements, on the theory that they were unreachable. But the code in these if (0) statements _is_ reachable, via the case labels related to the containing switch. So the compiler had thrown away code that was actually needed, and then got confused when it couldn't generate the jump for those switch cases.

    (The more usual strategy is to start by turning the whole function into a control-flow graph, i.e. blocks of straight-line code in a directed graph connected by edges that are effectively gotos. Then you can optimise conditional branches based on a constant into unconditional branches, deleting the never-traversed graph edge out of their block. Then you detect unreachable code by a search through the graph from the function entry point. That strategy avoids this problem.)

    💬 8🔄 13⭐ 95
  • Nov 21, 2026, 10:23 AM

    The fifth escape sequence in the switch, ESC # 8, is one of the most fun ones in the whole terminal. It instantly replaces the entire screen contents with copies of the capital letter E.

    In DEC's documentation it goes by the name DECALN, and is described as an alignment test. I guess the point is that it's a quick way to put text in every part of the screen, if you're about to check that your old-fashioned CRT monitor is showing the whole of the terminal contents, and not e.g. missing half a row or column because it's off one edge of the display.

    I was fascinated by that sequence as a child, partly because it's amusing, and also because of the way that it _instantly_ updated the screen, which I didn't know how to do any other way (the machines I was using were slow and I was writing in high-level languages). It stuck in my head all my life for that reason.

    And I eventually found a real use for it! Once I wanted to train myself out of the bad habit of using backticks in my shell commands (the synonym $(...) is better, because it nests sensibly and doesn't impose extra escaping needs on its interior). So I bound the ` key in bash to a command that echoed ESC#8, which was just the right level of reminder to not do that again – it didn't make a loud noise annoying my colleagues, or destroy any work, but it definitely reminded me to change that habit. After about a month, I'd got into the new habit and removed the binding.

    💬 7🔄 12⭐ 128
  • Nov 21, 2026, 11:12 AM

    @simontatham code so bad it makes using a goto statement the more readable variant. what a world we live in.

    💬 1🔄 2⭐ 37
  • Nov 23, 2026, 8:46 AM

    @bnuuy @simontatham using gotos is perfectly reasonable in the right circumstances, forbidding goto because they can make the code hard to read when used wrong is like banning ternary expressions for the same reasons, it's simply overkill. reality is more nuanced than what is taught in school

    💬 1🔄 0⭐ 0
  • Nov 23, 2026, 9:57 AM

    @SRAZKVT @simontatham you should probably carefully reread the thing i wrote, and the thing it was in response to.

    "don't use goto" is usually still good advice. the times i'd let you off the hook for using it are exactly when you can actually justify that it is (give or take) more readable than alternatives, which is rarely the case.

    and even if someone thought goto was absolutely never acceptable: 100% of programs, can, in principle, be written without it. you would not loose any amount of expressive power. whether and when you want to make exceptions ot the general rule is somewhat up to taste/personal preferences/what is idiomatic in a given language/project.

    and, if you really want, you can write horrible spaghetti code in any language, without ever touching goto. goto is just the thing that makes it easy, especially if you use it to avoid properly structuring your program, which used to be a lot more common than it is now.

    💬 1🔄 0⭐ 0
  • Nov 23, 2026, 10:22 AM

    @bnuuy @simontatham and i'm saying goto isn't shameful, writing hard to read code is. so long as the code is understandable, it doesn't matter what statements are used, and requiring a justification for a goto but not anything else is completely arbitrary

    i agree that gotos used wrong will lead to spaghetti, they're like everything, but it would be a dramatic increase in code quality to actually document cases where using a goto is reasonable, rather than shaming people away from using it with an extremely exception, which is what you're doing

    💬 1🔄 0⭐ 0
  • Nov 23, 2026, 10:26 AM

    @SRAZKVT @bnuuy in C in particular, goto is surprisingly often the best answer. The common idiom of shared cleanup paths at the end of a function, for example: 'goto fail' notwithstanding, it's still less risky overall than a bajillion early exit paths that all have to separately remember to clean up the right subset of resources.

    You could certainly argue that this is working around a weakness of C. In a more powerful language, destructors / drop handlers / finally / RAII in general would do this job. Similarly for other 'yes but there's no better choice' uses of goto in C. But if you're _in_ C, you do have to work around those weaknesses.

    A long time ago I developed the habit of writing /* sorry */ to the right of every goto statement. I think that's about the right level of discouragement. It's not "never write a goto", but "be aware that it's not ideal when you do it, and think about whether you have a better option".

    💬 1🔄 1⭐ 0
  • Nov 23, 2026, 1:37 PM

    @simontatham @SRAZKVT @bnuuy I would argue that many exception handling features are just obscured gotos with social license.

    What I have found is that certain logic that is clearly expressed via flowchart and gotos is difficult to implement gracefully or elegantly through structured logic.

    Emphasis: _IT IS RARE_ but it exists and it's a serious pain in the ass to refactor away. I'm not sure it's worth the effort.

    💬 2🔄 1⭐ 0
  • Nov 23, 2026, 1:54 PM

    @arclight @simontatham @SRAZKVT error handling is still hard pretty much everywhere, the other part of it is that they are boring codepaths that surely, would basically *never* happen (how would they even trigger?), but still need exactly the same amount of attention as the main "happy" code path just the same.

    exceptions are really just alternate (non-first class) continuations, a fancy functional programming goto-flavoured construct, yet something of this shape is forced by how typically the code that would know how to handle a problem and the code that would detect there is a problem typically live some number of stack frames apart. maybe one day programming languages will come up with better mechanisms, if the LLM dark ages ever end.

    💬 0🔄 0⭐ 0
  • Nov 23, 2026, 1:54 PM

    @arclight @SRAZKVT @bnuuy "many exception handling features are just obscured gotos with social license" – you could say the same about control flow constructions in general! All the standard things like 'if' and 'while' and 'for' are turned into machine-code branch instructions in the end, so they're just a way to specify a set of gotos in a formulaic structure.

    As I said in another subthread, the nasty thing about gotos in C is that there's one namespace of labels across the whole function. If you implemented, say, 'while' in terms of goto, you'd have to make a set of named labels for each separate while loop, and it would be legal but almost certainly a mistake to write a label relevant to _that_ while loop in the middle of _this_ one.

    (For example, imagine cut/pasting some code with the semantics "if (condition) break" from one loop into another, and forgetting to change the name of the break label. In assembly language this can be even worse, because there's one space of labels across the whole _file_, even if it contains multiple functions.)

    So the dangerous thing about goto is not that it does a jump; it's that it can do _any jump at all_. Every higher-level construction that wraps a goto is really making a locked-down version of goto, which makes it easy to do the jump you actually meant, and hard to do some other very similar jump by mistake. It's not primarily the social acceptability: that's a consequence of the restrictedness.

    💬 0🔄 0⭐ 0
  • 💬 1🔄 1⭐ 10
  • Nov 21, 2026, 10:47 PM

    @idiot @simontatham Sounds like a perfectly reasonable childhood. I recently uncovered a crusty print out of ANSI control sequences I made when I was like 15. For young me, this was like getting my hands on the dead sea scrolls or something. Basically a religious artifact.

    Printout of a table of ANSI control sequences with a few smudges and coffee stains.
    💬 1🔄 1⭐ 6
  • 💬 0🔄 0⭐ 3
  • 💬 0🔄 30⭐ 96
  • Nov 21, 2026, 11:39 PM

    @simontatham $() was a bashism for the longest time.

    I'm vaguely surprised that it has been standardized since 2008.

    I suppose then that if one is using platforms that are all newer than 2008 and implement up-to-date POSIX of that time then it's fine.

    💬 2🔄 0⭐ 0
  • 💬 2🔄 0⭐ 0
  • 💬 1🔄 0⭐ 0
  • 💬 1🔄 0⭐ 0
  • 💬 1🔄 0⭐ 0
  • 💬 0🔄 0⭐ 0
  • 💬 0🔄 0⭐ 0
  • 💬 0🔄 0⭐ 0
  • 💬 2🔄 0⭐ 0
  • 💬 0🔄 0⭐ 0
  • 💬 1🔄 0⭐ 0
  • 💬 0🔄 1⭐ 0
  • 💬 1🔄 0⭐ 1
  • 💬 0🔄 0⭐ 0
  • 💬 0🔄 0⭐ 0
  • 💬 0🔄 0⭐ 0
  • 💬 0🔄 0⭐ 0
  • 💬 0🔄 0⭐ 3
  • 💬 0🔄 0⭐ 1
  • 💬 0🔄 1⭐ 12
  • 💬 0🔄 0⭐ 0
  • 💬 0🔄 0⭐ 0
  • Nov 22, 2026, 12:23 PM

    @simontatham I once used a variant of Duff's device in some code at work. It broke the compulsory (and useless) linter they used, but it was so much faster that a special exception was reluctantly granted.

    💬 0🔄 1⭐ 0
  • 💬 0🔄 0⭐ 0
  • 💬 2🔄 0⭐ 14
  • 💬 0🔄 0⭐ 9
  • 💬 1🔄 2⭐ 0
  • Nov 21, 2026, 10:41 AM

    @barubary I once experimented with a macro called 'since', which looks like a control flow statement, and has the semantics that it checks its condition by assert() and then unconditionally executes the body.

    if (x > 0) {
    // do this
    } else if (x == 0) {
    // do that
    } else since (x < 0) {
    // do the other
    }

    💬 1🔄 3⭐ 15
  • 💬 1🔄 0⭐ 0
  • 💬 1🔄 0⭐ 2
  • Nov 21, 2026, 10:59 AM

    @barubary @mirabilos yes, I think that was more or less what I did, although I might have been on the ball enough to avoid leaving the if unbalanced:

    # define since(condition) if (assert(condition), 0); else

    But I didn't have to go as far as the alternative technique I invented much later, which would have looked something like this:

    # define since(condition) \
    if (1) { \
    assert(condition); \
    goto MAKE_LABEL; \
    } else \
    MAKE_LABEL:

    where MAKE_LABEL in turn creates a label name by token-pasting on to __LINE__, so that you can do this more than once in a function without getting duplicate label errors.

    (Doing it this way you wouldn't be allowed to write more than one 'since' on the same source line. Probably nobody cares, but it is a weakness of this technique in principle. The simpler approach with the comma operator is better, in cases where it works.)

    💬 2🔄 0⭐ 3
  • 💬 1🔄 0⭐ 0
  • 💬 2🔄 0⭐ 0
  • Nov 21, 2026, 11:17 AM

    @mirabilos @barubary it's in gcc 13.3, on my Ubuntu 24.04 system.

    If I remember rightly, __COUNTER__ was originally an MSVC-ism. But of course any compiler with a sufficiently thorough MSVC compat mode would have to implement it for that mode. And then they might decide to turn it on everywhere, on the principle that it's easy, compliant (we're in the __ namespace) and might well come in useful.

    I've occasionally wondered about changing over the case-generation macros in my coroutine system to use it (where available), eliminating the restriction about two yields on the same line, and also packing the case values more tightly so that the compiler is more likely to be able to generate an efficient dispatch table. But eliminating that restriction is a double-edged sword, because if not _all_ C compilers support __COUNTER__, it puts you at more risk of writing code that works for you but not for everyone else who needs it.

    And __COUNTER__ still isn't in standard C, as of C23.

    💬 1🔄 0⭐ 4
  • 💬 0🔄 0⭐ 0
  • 💬 1🔄 0⭐ 1
  • Nov 21, 2026, 11:35 AM

    @simontatham @barubary 3.4, any newer is not a good fit for the base system because if licence reasons and because it makes the boot floppy not fit any more and because of slop, plus this one works well for gpc

    💬 0🔄 0⭐ 0
  • 💬 0🔄 0⭐ 0
  • 💬 0🔄 0⭐ 3
  • 💬 0🔄 0⭐ 2
  • 💬 1🔄 0⭐ 0
  • Nov 21, 2026, 10:36 AM

    @mirabilos in the email introducing Duff's device, Tom Duff mentioned the (mis)feature of C that switches don't automatically break after case labels. ("This code forms some sort of argument in that debate, but I'm not sure whether it's for or against.")

    In fact, I think the _more_ critical (mis)feature of C switches is the way that the labels are allowed to appear inside sub-blocks. _All_ switch abuse concepts I know of make use of that: Tom Duff's unrolled loop, my ad-hoc coroutine mechanics, and this. But not all of them depend on the lack of implicit break – if that were different, my coroutine system would still have worked fine, I'd just have to add an extra goto in the macro implementing 'yield' to jump past the case label.

    💬 1🔄 3⭐ 9