简体   繁体   中英

Why doesn't omitting “case” in switch…case throw error or warning in XCode?

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?

  1. Is there something in the structure of the language that makes a switch case harder to interpret?
  2. Is there ever an instance in which you would want to omit the case statement to produce some other behavior (which I know nothing about)?
  3. 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 no case statements is legal, although a bit strange.

That said, clang will emit a warning upon seeing a switch statement with no case statements. Are you using GCC?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM