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;
}
}
43
Upvotes
View all comments
Show parent comment
2
u/bzzzt_beep Apr 22 '26
its a miscommunication, we are having the same side regarding branching cycles (switch is less cycles). in computation cycles, I was referring to the bitwise arithmetic (
<<,&,|,~). But likely branch misprediction risk more cycles.OK :
#define AXIS_Y 0 // 00#define AXIS_P 1 // 01#define AXIS_R 2 // 10#define GAIN_P 0 // 00#define GAIN_I 1 // 01#define GAIN_D 2 // 10// (axis index << 2) | gain index#define PK(a, g) (((a) << 2) | (g))void update_gain() {char g, gg;double value;if (scanf(" %c %c %lf", &g, &gg, &value) != 3) return;char *a_list = "ypr", *g_list = "pid";char *a_ptr = strchr(a_list, g);char *g_ptr = strchr(g_list, gg);if (a_ptr && g_ptr) {uint8_t id = PK(a_ptr - a_list, g_ptr - g_list);switch (id) {case PK(AXIS_Y, GAIN_P): p_gain_y = value; break;case PK(AXIS_Y, GAIN_I): i_gain_y = value; break;case PK(AXIS_Y, GAIN_D): d_gain_y = value; break;case PK(AXIS_P, GAIN_P): p_gain_p = value; break;case PK(AXIS_P, GAIN_I): i_gain_p = value; break;case PK(AXIS_P, GAIN_D): d_gain_p = value; break;case PK(AXIS_R, GAIN_P): p_gain_r = value; break;case PK(AXIS_R, GAIN_I): i_gain_r = value; break;case PK(AXIS_R, GAIN_D): d_gain_r = value; break;}}}