Switch statement not doing what I expect

后端 未结 4 2021
悲&欢浪女
悲&欢浪女 2020-12-12 07:50

What is wrong with this code:

switch (n)
{
    case 0:   strcpy(resultString, \"Zero\");
    case 1:   strcpy(resultString, \"One\");
    case 2:   strcpy(re         


        
相关标签:
4条回答
  • 2020-12-12 08:17

    You need to break after each case.

    case 0: 
    
    do soemthing;
    
     break;
    
    case 1:
    
     do something;
    
     break;
    

    In many managed languages, it won't let "one case fall through to another," and throws an error. But C loves to let you do whatever you want!

    0 讨论(0)
  • 2020-12-12 08:18

    You need a break statement at the end of each case. Otherwise control falls straight through to the next case.

    Change your code to:

    switch (n)
    {
        case 0: strcpy(resultString, "Zero"); 
                break;
        case 1: strcpy(resultString, "One"); 
                break;
        case 2: strcpy(resultString, "Two"); 
                break;
        case 3: strcpy(resultString, "Three"); 
                break;
        case 4: strcpy(resultString, "Four"); 
                break;
        case 5: strcpy(resultString, "Five"); 
                break;
        case 6: strcpy(resultString, "Six"); 
                break;
        case 7: strcpy(resultString, "Seven"); 
                break;
        case 8: strcpy(resultString, "Eight"); 
                break;
        case 9: strcpy(resultString, "Nine"); 
                break;
    }
    printf("%s", resultString);
    

    You can find the switch statement documented here or in any book on the C language.

    0 讨论(0)
  • 2020-12-12 08:31

    From the standard :

    6.4.2 The switch statement [stmt.switch]

    case and default labels in themselves do not alter the flow of control, which continues unimpeded across such labels. To exit from a switch, see break (6.6.1).

    6.6.1 The break statement [stmt.break]

    The break statement shall occur only in an iteration-statement or a switch statement and causes termination of the smallest enclosing iteration-statement or switch statement; control passes to the statement following the terminated statement, if any.

    That means that is you don't use break after each case, you program will enter in the first case who matches the condition and will continue executing every line of the switch until the end.

    You should just do something like :

    switch( n )
    {
        case 0:
            // ...
            break; // <- Note the break
        //...
    
        default:
            // ...
    }
    
    0 讨论(0)
  • 2020-12-12 08:37

    You missed break; after each case

    Example :
     case 0:   strcpy(resultString, "Zero");break;
     ..
     ..
     case 8: .... ; break;
     ..
    
    0 讨论(0)
提交回复
热议问题