While inspecting a non-functioning bit of code, I realized that I’d left the “case” out of my switch statements. The buggy code had the following format
switch (foo) {
firstElem:
...
break;
secondElem:
...
break;
}
Where firstElem and secondElem are part of an enumerated list. When I step through the code, it jumps from switch to the closing bracket, since it finds no match.
This was simple to fix, but it left me uneasy because XCode did not complain at all either at compile or run-time. Why?
- Is there something in the structure of the language that makes a
switch caseharder to interpret? - Is there ever an instance in which you would want to omit the
casestatement to produce some other behavior (which I know nothing about)? - Does this happen in other languages? I know Objective-C is a “strict superset of C,” so I assume the same might happen in C (depending on the compiler). What about Java? C++?
UPDATE: I’m using XCode 4.4.1 (although I’ll go and upgrade in a sec). This is part of an established project.**
FURTHER UPDATE AND REFERENCE Kevin Ballard correctly pointed out that I was accidentally defining labels. For more info on labels and GOTO, you can find a discussion in The C Programming Language 3.8 in which Kernighan and Richie conclude that (although they might have some use in error checking)
… code that relies on goto statements is generally harder to understand and to maintain than code without gotos. Although we are not dogmatic about the matter, it does seem that goto statements should be used rarely, if at all.
What you have is a bunch of regular old labels inside your
switch. That’s perfectly legal. Xcode isn’t complaining because a switch with nocasestatements is legal, although a bit strange.That said,
clangwill emit a warning upon seeing aswitchstatement with nocasestatements. Are you using GCC?