break statement does not work outside of switch or loop?

I was just messing around in Xcode and I discovered that, when I tried to use the break statement to exit a block of code, I got an error ("break statement not within loop or switch"). I thought the break statement was supposed to be able to be used to exit any block of code at any time, so I opened my Mac OS X Programming book by Wrox (a bit outdated, uses older version of Xcode/Interface Builder, but applicable enough), and the book confirmed that I should be able to use the break statement within any block of code, not just switch/case construction and loops. I assume something has changed in the newer version of Xcode since this book has been published, but I'm curious, so can anyone explain this to me? Thanks!

MacBook, Mac OS X (10.5.7)

Posted on Aug 31, 2009 2:14 AM

Reply
5 replies

Sep 1, 2009 1:44 AM in response to Tron55555

Yeah, that seems to be the case, and that's the only way I've ever used "break," but I did think it could be used to exit any block of code, especially having read it in the book I have. The book is Mac OS X Programming by Wrox, and on page 175 in the "The C Language" chapter, it says:


"break" is not only useful for "switch" and "while" statements; it can actually be used anytime you want to escape a block of code enclosed in braces. Execution is immediately transferred to the closing brace, and continues from there."

Anyways, I guess it is possible that in some older standard of C the "break" statement was allowed in these cases, since I can't imagine the book being out and out wrong, but you're right, it certainly seems to be -- interesting...

Sep 1, 2009 8:37 AM in response to Tron55555

Sounds like your book is mistaken - I checked the K&R C book, and section 9.6 (Jump Statements) says "A break statement may appear only in an iteration statement or a switch statement, and terminates execution of the smallest enclosing such statement".

And it makes sense too - you can "escape" from a method with "return" , and you can skip code in other situations with an if/else. I don't know what a "break" outside a case would be expected to do.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

break statement does not work outside of switch or loop?

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.