Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

Breaking Out

We’ve already seen the break command used to end a case clause in a switch statement. It transfers execution to the first statement after the switch. The break command can also be used inside iteration loops to exit them unconditionally. Like any unconditional jump statement (or chainsaw, for that matter), the break statement should be used with caution. But used correctly, it can make your code more efficient and much easier to understand. Let’s look at an example of the kind of problem the break statement can solve:

image

To understand what’s wrong with this code, ask yourself some questions:

• How many times does this loop get executed if b is equal to 5? How many times does it get executed if b is equal to 100?

• Does the value of b affect the value of a at the end of the loop?


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


 Â