Please share...

  • Video courses

    All game programming videos just $19 - For a very limited time these three videos and thousands more are up to 90% off!

    Just enter coupon code NEWU19 in cart/checkout

The Unreal Engine Developer Course – Learn C++ & Make Games

Learn and Understand C++

Over 260 video lectures in 44 hours of video!

Learn C++: Beginner to Advanced

Join thousands of successful students!

Condition checking in games is all about making decisions. How do we know if the player has run out of lives? How do we detect if the ball has reached the edge of the screen and needs to bounce back the other way? C++ has the if keyword which we can use to code our condition checks.

About this tutorial

Skill level 1
Time to read: 10 minutes

New Concepts:

  1. Decisions in C++
  2. if
  3. Logical AND &&
  4. Logical OR ||

We need to be able to use C++ to ask questions, perhaps things like this:

if the ball has reached the edge of the screen.

	Reverse the direction of the ball.

if the player loses his last life. 

	End the game.

Note that the above is pseudo code to demonstrate how if works. It is not actual C++. We will see real C++ code using  if soon as well as a practical runnable example in a few tutorials time. We will use pseudo code from time to time to help explain things. It will usually be obvious when it is pseudo code but I will point it out when necessary.

Also, note how the action (e.g. Reverse the direction of the ball) is indented from the edge of the page? We will use indents a fair amount to make our code more readable and I strongly encourage you to do the same.

Some more pseudo code but getting nearer to real C++ is this:

if(some condition is true) {

	// do whatever

}

The if keyword is followed by the opening and closing parentheses (). Inside the parentheses, we have a condition and afterwards, contained in opening and closing curly braces {} we have the code that will run if the condition is true. Note that it is possible to omit the curly braces if there is only one line of code that should be executed if the condition is true. It is extra clear however if we do use the curly braces and most of the time in the tutorials on this site, that is what we will do.

We will deal with the // do whatever part in the next tutorial. For this tutorial, we will look at the most useful possibilities we can use with the C++  if keyword to create conditions we can then test to see if they are true.

Let’s look at some more operators this time, some comparison operators that we can use to check for conditions in our games.

  • Beginning C++ Game Programming

    Beginning C++ Game Programming

    This book is all about offering you a very fast and fun introduction to the world of game programming and C++. It will begin by teaching you the programming basics such as variables, loops, and conditions. In this book there is very little theorizing. If you want a deep discussion of all the ins and outs of C++ concepts look elsewhere. If you are starting from a knowledge of zero C++ and want to build great games- fast, take a look at this book.
    • Setup a C++/SFML/Visual Studio development environment
    • Build a fast, fun Timber clone after learning basic C++
    • Discover the fundamentals of C++ object oriented programming and build a multi-level, top-down 2D, scrolling zombie survival/shooter
    • Explore some advanced C++ concepts and make a side scrolling, co-op split-screen multiplayer platform game with directional sound, particle effects and your very own level designs!
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US only)
    C++ for Game programmers book

    C++ For Game Programmers

    Already know the basics of C++ but want to dig much deeper in an entirely game-focussed context? C++ for Game Programmers is that book. This best selling title supplements your knowledge by putting everything into perspective from a game-development point of view. The book points out the most effective C++ practices and steers you away from the potentially dangerous ones. It describes common C++ techniques to solve specific problems most game developers face.
    • From a gaming perspective, learn about inheritance, performance, memory management, and STL to object creation, object serialization, and scripting languages
    • Explore C++ Design Patterns and high-level problem-solving constructs that are most commonly found in games
    • Discover custom Structures and algorithms, which provides a detailed hands-on discussion of using C++ to create efficient solutions to difficult problems in a highly structured manner
    Amazon USA
    Amazon UK
    Amazon CA
    Game Programming Patterns book

    Game Programming Patterns

    If you are serious about writing high quality, reusable, efficient code using C++ or indeed any other language, then inevitably you will need to seriously hone your knowledge of game programming patterns. If you don't know what game programming patterns are they are simply the solutions to design problems. If you have programmed even a basic game you will have noticed that the code gets long and hard to manage, very quickly. The more features you add the more sprawling and messy your code gets. In addition to usability/reuse-ability, our game code needs to be efficient enough for the game to run smoothly. That's what this book will do for you.
    • Learn to write a robust game loop, how to organize your entities using components, and take advantage of the CPUs cache to improve your performance
    • Discover how to organize your entities using components, and take advantage of the CPUs cache to improve your performance.
    • Never again wonder what is the "best" way to organize your game code
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US only)

C++ Comparison operators

We can already add ( +), take away ( -), multiply( *), divide ( /), assign ( =), increment ( ++), and decrement ( --) with operators. Let’s introduce some more super-useful operators and see how to actually use them in C++. Don’t worry about memorizing every operator given here. Just glance at them and their explanations and then move quickly on to the next section.

Note that in all the examples that follow we invent some variables. For any of these examples to work the variables would need to be declared and initialized.

First, we have == which is the equality or comparison operator, not to be confused with the assignment operator =. It tests for equality and is either true or false. We can create and test conditions like this.

if(playerLives == 0){

	// End the game.

}

! is the logical NOT operator. Here it is in action.


if(!playing){

	// Quit to main menu

}

!= This is another comparison operator, which tests if something is NOT equal. For example:


if(playerAnswer != actualAnswer){

	// Player has got it wrong

}

>: This is another comparison operator, which tests if something is greater than something else. The expression:


if(ballPositionX > screenWidth){

    // passed the edge of the screen
    // reverse the direction of the ball.

}

>=: This operator tests whether one value is greater than or equal to the other, and if either is true, the result is true. Notice in the next two examples we can use literal values in if statements as well as variables. For example, the expression:


if(10 >= 9){

	// is true.

}

Also look at this for further clarification.


if(10 >= 10){ 

	// is also true because 10 equals 10
	// even though 10 is not greater than 10

<=: Like the preceding operator, this operator tests for two conditions but this time, less than or equal to. The expression,


if(10 <= 9){ 

	// is false.

}

However, both of these conditions are true.


if (10 <= 10){

	// is true because 10 equals 10

}

if (9 <= 10){

	// is true because 9 less than 10

}

&&: This operator is known as logical AND. It tests two or more separate parts of an expression and ALL parts must be true in order for the result to be true. Logical AND is usually used in conjunction with the other operators to build more complex tests. The expression:


if((10 > 9) && (10 < 11)){

	// is true because both parts are true.

}

However this turns out false:


if((10 > 9) && (10 < 9)){
	// is false because only one part of the expression
 	// is true (10 > 9) and the other is false (10 < 9).

}

|| This operator is called logical OR. It is just like logical AND except that only one of two or more parts of an expression need to be true for the expression to be true. Let’s look at the last example we used but replace the && sign with ||. The expression,


if((10 > 9) || (10 < 9)){
	// is now true because...
 	// one part of the expression is true (10 > 9)

}

Here are a few examples. You don’t need to fully understand how the code in the next few samples works just take a look at it and think about how we are controlling our game code with the if statements and their conditions. This is real code from a game using the SFML game library.

bool hitDetected = false;

// Some C++ that detects
// if the player ship was hit goes here

if(hitDetected) {

	sound.play(explosion);
	playerLives --;

}

Now look at how we might check to see if the player had got a new fastest time at the end of a racing game. As with the other examples, we assume the variables would have been declared and initialized previously.

//check for new fastest time

if(timeTaken < fastestTime) {

	// the player took less time than the fastest time!!
	// So a new fastest time has been set

	// Now change the the fastest time variable
	// to the new fastest time (timeTaken)
	fastestTime = timeTaken;

}

We have spent allot of time detecting conditions and making decisions but apart from that very last example we haven’t actually done anything when a condition has been detected as true. Let’s look at how we can structure our C++ game code to get stuff done. Note that almost any code at all can go inside the curly braces {} of an if statement (including more if statements). In the next tutorial we will see that we can branch our game code based on the conditions we have just learnt to test for. Take a look at how to branch our game code.