DDPWNAGE
DDPWNAGE

Reputation: 1443

Xcode "switch/case" statement - warning about break;

What constantly happens to me is this, when I'm using Xcode with Objective-C:

I'll be writing a switch/case statement. Typically, to make sure statements are separated, the programmer must make sure there are break;s between cases.

I often forget to put the break; statement in, so instead of the device executing only the the desired case, the device executes the case and then the case after it. This happens on both a physical device (iPhone 6) and on every simulated device on iOS Simulator.

Here's what the syntax of the failed statement looks like, with someInt being a number that is either 0 or 1:

switch (someInt)
{
    case 0:
    {
         // some statements to execute if "someInt" is 0
    }
    case 1:
    {
         // some statements to execute if "someInt" is 1
         break;
    }
}

Note how, in case 0:, there is no break; statement. This causes case 0: to execute and then case 1 to execute, instead of just case 0 to execute.

Is there a way I can put a flag in Xcode so it warns me if I forget a break; statement?

I know many programmers have probably been confused for days, weeks on end, because of this problem.

Upvotes: 1

Views: 1464

Answers (2)

Paulw11
Paulw11

Reputation: 114773

This behaviour is an implicit part of the C language (which underlies Objective C) and although more often than not, you don't want the fall through to the next case, for better or worse, this is the way the language is defined.

Swift, on the other hand, doesn't require an explicit break as cases do not fall through.

Clang does define a warning -Wimplicit-fallthrough which generates a warning in the situation you describe, however it doesn't seem to be supported in the Clang included with Xcode 6.3.2. I don't have Xcode 7 installed yet to check if this is still true in that version.

Upvotes: 1

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16650

I do not think that there is a compiler warning. This is, because "the programmer must make sure there are breaks between cases." is not fully correct. The programmer must make sure that there are breaks between the cases, if he wants the code not to fall through. (There are use cases for falling through.)

The background is that C was akin of replacement for assembler. In assembler you write a multi-selection with conditional jumps to the specific branch (case) and unconditionally jumps out of a branch (break), if you do not want to continue. (BTW: This is the reason for being case-branches no blocks, too.)

Of course, this is obsolete. You can simply use the automatic code generation of Xcode or replace switches with if-else if-else cascades.

Upvotes: 2

Related Questions