NESTING CONDITIONAL LOGIC


Sometimes your application's logic is too complicated to be represented using the different variations of the if statements. If this is the case, you can greatly extend the power of the if statements by nesting them within one another. Nesting enables you to develop logic that tests for one condition and then further tests other conditions based on the result of the previous test.

Hint 

Nesting is the process of embedding one statement within another statement of the same type, such as when you embed if statements to develop more complicated conditional logic.

You've already seen examples of nested if statements in previous chapter game projects. For example, the following code comes from the btnDone_Click event belonging to the Speed Typing game that you built in Chapter 3.

 //Handle three strikes if( intWrong == 3 ) {   //Inform player that he's a beginner   if( intCount < 2 )   {     MessageBox::Show( "Game Over! Your "     "typing skill level is: Beginner. "     "Please play again!" );     intCount = 0;     intWrong = 0;     return;   }   //Inform player that he's intermediate   if( intCount < 4 )   {     MessageBox::Show( "Game Over! Your "     "typing skill level is: Intermediate. "     "Please play again!" );     intCount = 0;     intWrong = 0;     return;   }   //Inform player that he's advanced   if( intCount < 5 )   {     MessageBox::Show( "Game Over! Your "     "typing skill level is: Advanced. "     "Please play again!" );     intCount = 0;     intWrong = 0;     return;   } } 

In the Speed Typing game, the game ends if the player receives three strikes. The number of strikes is stored in the intWrong variable. The game also tracks the number of typing tests passed by incrementing the value assigned to the IntCount variable.

In this example, the value of intWrong is tested first to see if it is equal to 3. If this is the case, a series of three nested if statements is executed. Each further refines the logical condition that the game needs to test for by checking the value assigned to the intCount variable. This creates a more sophisticated test whereby messages are displayed to the player and variables are reset based on both the intWrong and intCount variables matching certain conditions.

Trap 

Try to avoid using more than one level of nested if statements. Having several layers of nested if statements within any given if statement can make for code that is difficult to follow logically.




Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
ISBN: 735615381
EAN: N/A
Year: 2005
Pages: 131

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net