We have seen in the last tutorial how we can detect certain conditions in our C++ code. For example when the player loses a life, destroys an alien or gets a new fastest time. We have also seen the C++
if keyword that allows us to execute a certain block of code when a particular condition or even multiple conditions are met. It is this concept of branching our code based on certain conditions that we need to explore a little further.
[widgets_on_pages id=”udemy_advert_cpp_1″][widgets_on_pages id=”udemy_code_details”]
We will learn about two more conditional branching branching concepts which is really just a closer look at if and some more related keywords.
C++ Conditional branching
As with many topics in C++ you could write a whole book on structuring code. What we will do is cover just enough so we can move our practical projects to a higher level. Here are the vital ways we can conditionally branch our code.
If they come over the bridge shoot them
The captain is dying and, knowing that his remaining subordinates are not very experienced, he decides to write a C++ program to convey his last orders after he has died. The troops must hold one side of a bridge while awaiting reinforcements. The first command the captain wants to make sure his troops understand is this:
If they come over the bridge, shoot them.
So how do we simulate this situation in C++? We need a bool variable isComingOverBridge. The next bit of code assumes that the isComingOverBridge variable has been previously declared and initialized. We can then use if like this.
if (isComingOverBridge) { // Shoot them }
If the bool isComingOverBridge is true the code inside the opening and closing curly braces will run. If not the program continues after the if block and without running it.
[widgets_on_pages id=”bcgp_cfgp_gpp”]
C++ else: do this instead
The captain also wants to tell his troops what to do (hold position) if the enemy is not coming over the bridge. Now we introduce another C++ keyword, else. When we want to explicitly do something when the if does not evaluate to true, we can use else. We can then use it like this to tell the troops to stay put if the enemy is not coming over the bridge:
if (isComingOverBridge) { //Shoot them } else { //Hold position }
The captain then realised that the problem wasn’t as simple as he first thought. What if the enemy comes come over the bridge, but they have more troops? His squad would be overrun. So, he came up with this code (we’ll show some variables as well this time.):
bool isComingOverTheBridge; int enemyTroops; int friendlyTroops; // Code that initializes the above variables one way or another // Now the if if (isComingOverTheBridge && friendlyTroops > enemyTroops) { //shoot them } else if(isComingOverTheBridge && friendlyTroops < enemyTroops) { //blow the bridge } else { //Hold position }
And finally the captain’s last concern was that if the enemy came over the bridge waving the white flag of surrender and were promptly slaughtered, then his men would end up as war criminals. The C++ code needed was obvious. Using the wavingWhiteFlag bool variable he wrote this test:
if (wavingWhiteFlag) { //Take prisoners }
But where to put this code was less clear. In the end, the captain opted for the following nested solution and changing the test for wavingWhiteFlag to logical NOT, like this:
if (!wavingWhiteFlag) { // not surrendering so check everything else if(isComingOverTheBridge && friendlyTroops > enemyTroops) { // shoot them } else if(isComingOverTheBridge && friendlyTroops < enemyTroops) { // blow the bridge } } else { // this is the else for our first if // Take prisoners { // Holding position
This demonstrates that we can nest
if and
else statements inside of one another to create even deeper decisions. We could go on making more and more complicated decisions but what we have seen is more than sufficient to make some fairly complex games in C++.
[widgets_on_pages id=”udemy_advert_cpp_2″][widgets_on_pages id=”udemy_code_details”]
Switching to make decisions
Sometimes a decision in C++ can be better made in other ways. When we have to make a decision based on a clear list of possible outcomes that doesn’t involve complex combinations or wide ranges of values, then switch is usually the way to go. We start a switch decision like this.
switch(argument){ }
In the previous example, argument could be an expression or a variable. Then within the curly braces we can make decisions based on the argument with case and break elements.
case x: //code to for x break; case y: //code for y break;
You can see in the previous example each case states a possible result and each break denotes the end of that case and the point that execution leaves the switch statement. We can also use default without a value to run some code in case none of the case statements evaluate to true. Like this:
default: // Look no value // Do something here if no other case statements are true break;
The best way of understanding all we have seen in this tutorial is to make a working project. Try out the Conditions and branching SFML project to reinforce what we have just learnt.
The next tutorial looks at how we can repeat sections of code in the c++ tutorial on looping our game code.
Hey, I’ve been looking for some cpp tutorials for a few days and finally stumbled into these, fantastic, I am familiar with logical functions and coding of different sorts so I’ve been having trouble making sense of other cpp forums that reference language I’m not familiar with like I should know it already, so far this lays it out perfectly for me. Thanks.
I planned on giving kudos when I’m further along but I noticed you didn’t provide a link to this tutorial at the end of the last like you have been so I thought I should point it out.
Thanksfor your comment. I will get that link fixed.
Nice tutorial, but I spot an error:
if (friendlyTroops == enemyTroops){
//they die, because nobody knows what to do
}
Well spotted! It should be greater than or equal to. Thanks for the comment.