Duff’s Device

We have heard enough about it. I was interested in knowing how it is legal C. Only Wikipedia has a word about this:

The device is valid, legal C by virtue of the relaxed specification of the switch statement in the language’s definition. At the time of the device’s invention this was the first edition of The C Programming Language which requires only that the controlled statement of the switch be a syntactically valid (compound) statement within which case labels can appear prefixing any sub-statement.

FOLDOC says that for maximum obfuscation, the switch braces can be removed to get a code like below. Looks definitely confusing, but should experiment with it more to understand what such statements are valid and what such statements are not valid. However, C bible book also says that cases are just convenient labels for statements.

    register n = (count + 7) / 8;
    switch (count % 8)
    case 0: do { *to = *from++;
    case 7:      *to = *from++;
    case 6:      *to = *from++;
    case 5:      *to = *from++;
    case 4:      *to = *from++;
    case 3:      *to = *from++;
    case 2:      *to = *from++;
    case 1:      *to = *from++;
    } while (--n > 0);
Advertisements

One thought on “Duff’s Device

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s