Switch statement not doing what I expect

后端 未结 4 2106
悲&欢浪女
悲&欢浪女 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: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:
            // ...
    }
    

提交回复
热议问题