Free Trial

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

Share this Page URL
Help

The Flight > do Loops - Pg. 38

38 l l Chapter 3 An MPLAB X compatible programmer/debugger such as the PICkit3, ICD3 or Real ICE The Explorer16 board, or any demo board with a row of eight LED connected to PortA. In preparation for the new demonstration project, you can make use of the New Project Setup checklist to create a new project called 3-MoreLoops. Also, use the New File wizard to create a new source file to be called MoreLoops.c. The Flight In a while loop, a block of code enclosed by two curly brackets is executed if, and for as long as, a logic expression returns a Boolean true value (not zero). The logic expression is evaluated before the loop, which means that if the expression returns false right from the beginning, the code inside the loop might never be executed. do Loops If you need a type of loop that gets executed at least once but only subsequent repetitions are dependent on a logic expression, then you have to look at a different type of loop. Let me introduce you to the do loop syntax: do { // your code here } while ( x); Don't be confused by the fact that the do loop syntax is using the while keyword again to close the loop ­ the behavior of the two loop types is very different. In a do loop, the code (if any) found between the curly brackets is always executed first, and only then is the logic expression evaluated. Of course, if all we want to achieve is an infinite loop for our main() function, then it makes no difference if we choose the do or the while... main() { // initialization code ... // main application loop do { ... } while ( 1); } // main Looking for curious cases, we might analyze the behavior of the following loop: do{ // your code segment here... } while ( 0); You will realize that the code segment inside the loop is going to be executed once and, no matter what, only once. In other words, the loop syntax around the code is, in this case, a total