繁体   English   中英

C switch case 值不能在 switch 内修改(不是常量)

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

我正在尝试在我在 arduino uno 上编程的游戏中创建弹跳动态。
我可以创建一系列嵌套的 if,但我听说 switch 更快。
我知道 case 值被指定为常量,但我很好奇是否可以使此代码工作?

// 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;
    }

我很确定答案是否定的,或者将变量放入常量的解决方法将比简单地放弃嵌套的 ifs 慢得多,而且大得多,但问起来并没有什么坏处。

Avi Berger 提出了一个很棒的解决方案,我能够适应并完成工作:

// 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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM