变量在切换情况下不起作用

Kri*_*rii -4 c++ arrays boolean

当我尝试编译以下内容时:

bool matrix[h][w];

bool c = 0;
switch(1) // was close?
{
  case matrix[y][x-1]: // up 1
  case matrix[y-2][x-1]: // down 1
  case matrix[y-1][x]: // right 1
  case matrix[y][x-2]: // left 1
    c = 1;
    break;
}
Run Code Online (Sandbox Code Playgroud)

它回来了the value of 'matrix' is not usable in a constant expression.我究竟做错了什么?

R S*_*ahu 7

语句中使用的case表达式需要是编译时常量.您可以使用:

case 1:

case 2:
Run Code Online (Sandbox Code Playgroud)

等等,不是

case matrix[y][x-1]: // up 1

case matrix[y-2][x-1]: // down 1
Run Code Online (Sandbox Code Playgroud)

此外,switch()的操作数应该是运行时变量,而不是编译时常量.例如,switch(matrix[y][x-1])没关系.