Skip to content

Instantly share code, notes, and snippets.

@benjamin051000
Created August 22, 2023 06:25
Show Gist options
  • Save benjamin051000/c6ed6addbcd97cb3e3ec49f8c8bcdf18 to your computer and use it in GitHub Desktop.
Save benjamin051000/c6ed6addbcd97cb3e3ec49f8c8bcdf18 to your computer and use it in GitHub Desktop.
duff's device: literal spaghetti code!
/**
* A demonstration of Duff's Device,
* which entangles a switch/case statement
* with another C idiom, like a do/while.
*
* https://en.wikipedia.org/wiki/Duff%27s_device
*/
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char** argv) {
if(argc < 2) {
return 1;
}
const int input = strtol(argv[1], NULL, 10);
printf("%d\n", input);
int n = (input + 3) / 4;
int output = 0;
// The good stuff
switch (input % 4) {
case 0: do { output++;
case 3: output++;
case 2: output++;
case 1: output++;
} while( n --> 0); // Another fun one: Equivalent to --n > 0
}
printf("%d\n", output);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment