【问题标题】:Variable will not work in switch case变量在 switch case 中不起作用
【发布时间】:2016-06-08 12:38:00
【问题描述】:

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

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

它返回the value of 'matrix' is not usable in a constant expression。我做错了什么?

【问题讨论】:

  • 您可能误解了switch 语句的作用。
  • @Krii 你想做什么?
  • @Zereges 那么 switch 语句的作用是什么?
  • 不幸的是,大小写必须保持不变。
  • 我不明白为什么这个问题被如此强烈地否决。用户提供了一个可重复性最低的示例,问题清晰有效;只是误解了某个功能的正确用法的结果。

标签: c++ arrays boolean


【解决方案1】:

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

case 1:

case 2:

等等,不是

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

case matrix[y-2][x-1]: // down 1

另外,switch() 的操作数应该是运行时变量,而不是编译时常量。例如,switch(matrix[y][x-1]) 就可以了。

【讨论】:

  • 另外,switch() 的操作数应该是运行时变量,而不是编译时常量。例如,switch(matrix[y][x-1]) 就可以了。
猜你喜欢
  • 1970-01-01
  • 2013-05-15
  • 2016-03-25
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-19
相关资源
最近更新 更多