pighead10
pighead10

Reputation: 4305

C++ for loop and switch statement logic error

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? How 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;
        }

Upvotes: 1

Views: 618

Answers (4)

Damon
Damon

Reputation: 70186

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).

Upvotes: 10

tobym
tobym

Reputation: 1344

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

Upvotes: 1

filmor
filmor

Reputation: 32258

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 ... { }.

Upvotes: 2

Loogawa
Loogawa

Reputation: 389

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)

Upvotes: 2

Related Questions