2

我有一个基于 int 比较的 switch 语句,但由于某种原因,它在真正的比较上一直失败,并跳到默认值。这是我的代码:

string Error(int errorNum, int send=1, int crash=1)
{
  string errorType;
  switch(errorNum)
  {
    case 10:
      errorType = "Port number";
    ...
    default:
      errorType = "Unknown";
  }
...
}

我一直用 的参数调用它10,但是当我这样做时,它失败了。equivelantif... else if... else方法有效,这里也是:

string Error(int errorNum, int send=1, int crash=1)
{
  string errorType;
  if (errorNum == 10)                 // Normally I'd use braces,
    errorType = "Port number";        // but here, it just clutters
  ...
  else
    errorType = "Unknown";
  ...
}
4

4 回答 4

4

If you don't use break then the all the subsequent case statements will be executed after the matching case.

So in your your case, it executes both the case parts and overwrites the value errorType which gives you the impression that it directly jumps to default case.


To add an interesting update...

Note that having braces around case statements would make no difference. In fact, the following code is valid C++ and would work as expected:

switch(var)
{

  {
   case 1:
     cout<<"case 1"<<endl;
  }
     cout<<"This is also part of case 1"<<endl;

   case 2:
  {
     cout<<"case 2 "<<endl;
  }

}

Note the braces are NOT misplaced.

Here the outside cout is also a part of the case 1. After evaluating the control expression var, control will jump straight to the matching case. The braces around case 1 merely introduces a new scope and has no bearing over what a case really constitutes. So right way is to put break statements if you don't want to fall-through the rest of cases.

于 2013-05-16T19:02:33.110 回答
4

You are likely missing a break in the case. Make sure that at the end of each case you include break or it will fall through to the next one.

string Error(int errorNum, int send=1, int crash=1)
{
  string errorType;
  switch(errorNum)
  {
    case 10:
      errorType = "Port number";
      break; // If this is not here it will fall throughto the next case or default

    default:
      errorType = "Unknown";
  }
  return errorType;
}
于 2013-05-16T19:02:45.270 回答
2

Do you have a break before default? If not then it will look like it is hitting default because it will fall through.

于 2013-05-16T19:03:09.553 回答
1

Each case statement will need a break clause, otherwise it will fall through to the next statement.

e.g.

   case 10: 
        errorType = "Port number";
        break;
    default: 
        errorType= "Unknown";
        break;

Look at http://msdn.microsoft.com/en-us/library/k0t5wee3(v=vs.80).aspx for more detail

Depending on your situation, it may even be better to return the string from within the switch. The return statement will not fall through

case 10: 
     return "Port number";
default: 
     return "Unknown";
于 2013-05-16T19:03:50.350 回答