Search code examples
objective-cswitch-statementxcode5

Switch always runs the same case statement Xcode 5


So I have a random word generator that uses a switch to randomly assign a word to a variable.

However, after some testing, I have discovered that it always runs 'case 2' and never case 0, 1 or default.

Here's my code:

int randWord1 = rand() % 2;
switch (randWord1) {
    case 0:
        mainTextView.text = @"1";


    case 1:
        mainTextView.text = @"2";


    case 2:
        mainTextView.text = @"3";

    break;

    default:
    break;
}

Edit:

After having the question closed for typos in the code, I discovered that the issue was that I had forgotten to add a break; statement after each case X: statement.


Solution

  • this is what you are missing:

    Case 0 {
    mainTextView.text = @"1";
    break;
    }
    
    Case 1 {
    mainTextView.text = @"2";
    break;
    }
    
    Case 2 {
    mainTextView.text = @"3";
    break;
    }
    Default:
    

    Notice the break in each Case x.

    In C, each case will execute if you don't put proper break statements before the next Case. In your situation, since Case 2 is the last case with any executable statements in it, you will always see mainTextView.text being set to 3. If, for sake of argument you had

    Default: {
    mainTextView.text = @"foo";
    break;
    }
    

    you would have seen foo printed every time because there was no break after Case 2: