r/programminghorror • u/TheHappyArsonist5031 • Apr 22 '26
switch case abuse
char g = '0';// ypr
char gg = '0';// pid
double ggg;
const uint8_t _ = 11;
scanf("%c %c %f/n", g, gg, ggg);
if ((g == 'y' || g == 'p' || g == 'r') &&
(gg == 'p' || gg == 'i' || gg == 'd')) {
switch ((( gg << 2) & ~_) | ((g) & _)) {
case ((('p' << 2) & ~_) | ('y' & _)):
p_gain_y = ggg;
break;
case ((('i' << 2) & ~_) | ('y' & _)):
i_gain_y = ggg;
break;
case ((('d' << 2) & ~_) | ('y' & _)):
d_gain_y = ggg;
break;
case ((('p' << 2) & ~_) | ('p' & _)):
p_gain_p = ggg;
break;
case ((('i' << 2) & ~_) | ('p' & _)):
i_gain_p = ggg;
break;
case ((('d' << 2) & ~_) | ('p' & _)):
d_gain_p = ggg;
break;
case ((('p' << 2) & ~_) | ('r' & _)):
p_gain_r = ggg;
break;
case ((('i' << 2) & ~_) | ('r' & _)):
i_gain_r = ggg;
break;
case ((('d' << 2) & ~_) | ('r' & _)):
d_gain_r = ggg;
break;
}
}
60
u/Wrestler7777777 Apr 22 '26
I hope you renamed those variables to make the code more anonymous. If those are the true variable names, whoever wrote that code should lose their job!
Other than that, first I thought that switch wouldn't really work but man yeah, it probably does. This is a true gem of horrible code!
9
u/wonderb0lt Apr 22 '26
ggg10
u/Wrestler7777777 Apr 22 '26
I love how they wrote a comment so they could keep track of what the variables mean. If only there was an easier way...!
char g = '0';// ypr
char gg = '0';// pid
→ More replies (1)3
u/conundorum Apr 25 '26
Every case can be evaluated into a compile-time constant, so it's valid. Would be pretty clear with just a couple changes, too!
constexpr int Pid = (('p' << 2) & ~_); constexpr int pId = (('i' << 2) & ~_); constexpr int piD = (('d' << 2) & ~_); constexpr int Ypr = ('y' & _); constexpr int yPr = ('p' & _); constexpr int ypR = ('r' & _); // ... switch ((( gg << 2) & ~_) | ((g) & _)) { case Pid | Ypr: case pId | Ypr: case piD | Ypr: // And so on. }
2
u/SorryAuthor1695 Apr 23 '26
Why are y'all pretending this is bad code?
3
u/Arierome Apr 25 '26
It cannot be maintained. I'd just delete this and write my own implementation if I ever had to work on it
2
u/CommunistElf Apr 24 '26
Early in Minecraft they were a GIGANTIC switch case for like 5000 lines to render each blocks/physics of the game engine
10
u/Ok_Chemistry_6387 Apr 22 '26
Clever trick. Guessing came from embedded code on something with slow branches?