Created
August 22, 2023 06:25
-
-
Save benjamin051000/c6ed6addbcd97cb3e3ec49f8c8bcdf18 to your computer and use it in GitHub Desktop.
duff's device: literal spaghetti code!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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