0

What is this called and how is it possible?

    switch (state_in->step){
        while (1){
            case step_a:
                // do something and fallthrough

            case step_b:
                // do something and fallthrough

            case step_c:
                // do something and fallthrough

            case step_d:
                // do something and fallthrough
        }
    }

snippet is from cdecode.c of the libb64 project. The state_in->step variable is not touched inside the loop, and code seems to iterate step_a->step_b->step_c->step_d->step_a->....

It seems as if switch acts as a smart goto statement, pointing inside a while loop? I would like to know how this thing works, but google only gives me switch inside a loop in C.

  • 1
    Its called Duff's device. – Avi Berger Sep 06 '22 at 21:13
  • Thanks @AviBerger , that answers the first question, now how is this a valid `C` syntax? – No Name Sep 06 '22 at 21:31
  • It is peculiar and surprising that it is legal. There are explanations in the linked duplicate post and on wikipedia. [And here are some messages about it by its inventor](http://www.lysator.liu.se/c/duffs-device.html) – Avi Berger Sep 06 '22 at 22:01

0 Answers0