Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C switch case values cannot be modified within the switch (not constant)

I am trying to create bounce dynamics in a game that I'm programming on an arduino uno.
I can create a series of nested ifs but I've heard that a switch is faster.
I know that the case values are specified to be constants, but I'm curious if it's possible to make this code work?

// player and ball are both byte arrays
    switch(ball[0]) { // bounce off edges x-axis
        case (player[0]-1):
            ball[3] -= 2;
            break;
        case player[0]:
            ball[3] -= 1;
            break;
        case (player[0]+3):
            ball[3] += 1;
            break;
        case (player[0]+4): // At this line the compiler says: the value of 'player' is not usable in a constant expression
            ball[3] += 2;
            break;
    }

I'm pretty sure that the answer is either no, or that the workaround of putting the variables into constants will be much slower and larger than simply giving in to the nested ifs, but it doesn't hurt to ask.

like image 803
Mikeologist Avatar asked Mar 12 '26 20:03

Mikeologist


1 Answers

Avi Berger presented a fantastic solution which I was able to fit and to make work:

// player and ball are both byte arrays
    switch(ball[0] - player[0]) { // bounce off edges x-axis
    case 1:
        ball[3] -= 2;
        break;
    case 0:
        ball[3] -= 1;
        break;
    case -3:
        ball[3] += 1;
        break;
    case -4:
        ball[3] += 2;
        break;
    }
like image 107
Mikeologist Avatar answered Mar 14 '26 09:03

Mikeologist