简体   繁体   中英

Why this code got “unreachable statement” error?

I have the following method :

  char getChar(int I)
  {
    if (I<65+26) return (char)(I);

    switch (I)
    {
      case 91 : return '?';break;
      case 92 : return '#';break;
      default : return ' ';
    }
  }

Why does it get "unreachable statement" error ?

Because you can't break after you have already return ed. return means "exit the method". break means "exit the block".

So if you have:

return '?'; break;

then the break can never be reached.

You probably don't need a break statement after a return , since control has already left the structure (even the entire method) by way of the return :

switch (I)
{
  case 91 : return '?';
  case 92 : return '#';
  default : return ' ';
}

Anything after a return would never be reached.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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