r/ProgrammerAnimemes • • Feb 20 '20

Duff's Device

Post image
933 Upvotes

21 comments sorted by

View all comments

Show parent comment

26

u/alblks Feb 20 '20

I'm not sure it will even compile

Of course it will. It's quite standard C syntax. Though maybe modern compilers will issue a warning about jumping into the middle of a cycle.

8

u/nwL_ Feb 20 '20

I’ve been programming C++ for 7 years now, and I have never encountered a syntax such as

case 0: do { ...
case 1: ...
case 2: ...
        } while (...)

I wouldn’t even know how to read it. Can you just jump into the middle of a loop? This is confusing.

7

u/bucket3432 Feb 20 '20

Yes, at least in C and I think also C++. The same applies to goto as well. I would be surprised if you ever see a jump into a loop body in modern code because it's almost always a bad idea: it's easily a potential source of bugs.

1

u/Da_rizzlah Aug 07 '26

It could be to hint to the compiler to generate a jump table for the function. A jump table is a list of addresses to jump to with numbers. It compresses a large number of if(){goto}s into a goto table[case].

6

u/bucket3432 Feb 20 '20

The original was written in K&R C, so I had to account for the possibility that they had changed a syntax rule that disallowed this with ANSI C. Furthermore, you have syntax like trigraphs that are perfectly valid C syntax, but gcc won't transform them by default unless you pass a flag. If you see my edit, it looks like you're right, it's fine, though I'm surprised I got no warnings.

2

u/WikiTextBot Feb 20 '20

Digraphs and trigraphs

In computer programming, digraphs and trigraphs are sequences of two and three characters, respectively, that appear in source code and, according to a programming language's specification, should be treated as if they were single characters.

Various reasons exist for using digraphs and trigraphs: keyboards may not have keys to cover the entire character set of the language, input of special characters may be difficult, text editors may reserve some characters for special use and so on. Trigraphs might also be used for some EBCDIC code pages that lack characters such as { and }.


[ ^PM | Exclude ^me | Exclude from ^subreddit | FAQ / ^Information | ^Source ] Downvote to remove | v0.28