开发者

C++ for loop and switch statement logic error

开发者 https://www.devze.com 2023-02-18 15:55 出处:网络
In this loop (assuming amount is 2), instead of printing: 1. [op1] 2. [op2] it prints: 1. [op1] 2. [op2] 3. [op3]

In this loop (assuming amount is 2), instead of printing:

1. [op1]
2. [op2]

it prints:

1. [op1]
2. [op2]
3. [op3]
4. [op4]
5. [op5]

Why? H开发者_StackOverflow中文版ow can I fix this?

for(int i=1;i<=amount;i++){
            //string s;
            switch(i){
            case 1:
                cout << i << ". " << op1 << endl;
                //s = op1;
            case 2:
                cout << i << ". " << op2 << endl;
                //s = op2;
            case 3:
                cout << i << ". " << op3 << endl;
                //s = op3;
            case 4:
                cout << i << ". " << op4 << endl;
                //s = op4;
            case 5:
                cout << i << ". " << op5 << endl;
                //s = op5;
            }
            //cout << i << ". " << s << endl;
        }


You need to use break; or switch() will have what's called "fallthrough".

(This means that it executes your case: and then continues on anything that comes afterwards, including code in other case statements).


You need to put

break;

at the end of each case. Otherwise it goes to case1, and then continues through to the end of the select. (case1, 2, 3, 4, 5)


You have to insert break;-statements at the end of each of your case:-parts.

This is because switch () {} is merely a reformulation of a goto, the cases are just labels, not real blocks (that's why they use the label-syntax instead of a block-syntax like case ... { }.


Put a "break" statement after the cases, otherwise the control flow will just go straight through.

0

精彩评论

暂无评论...
验证码 换一张
取 消