# Lesson 6: Simple if structure

Homework: http://beginnerscpp.com/forums/index.php/topic,60.0.html

If Statements
If statements are used to determine the course that our program will run in, based off whether a condition evaluates to being true, or false. The statement of if has 2 parts. if and the condition that it’s checking (which can have many parts). A simple if statement might look something like this:

or they can be much more complex, like this

In the first example we are simply checking if a number is equal to the number 2. Once we determine that is true, we add 5 to the number. The second example is something you might see in a game development scenario. A user is goes to cast a spell, there needs to be checks made against current values, and those are passed over to our if statements. We need for ALL of those conditions to be true for the spell to be cast (the user needs enough intellect to understand the spell, they need both mana and health, and they cannot be stunned) if any of those are not true, it will be passed to the else if (and then evaluated for truth there) then passed to else if that is not true either.

Classically if statements were represented (in flowcharting) as diamond layed on its side, with lines coming from the edges diagonally to illustrate that there were two paths that can be taken from an if statement (symbolizing an if and an else). While this is technically correct, it does lead to some questions among beginners for instance the following is VALID code

In the example above you will notice that there is no “else” attached to this if. So the earlier example showing two distinct “branches” might not always be clearly represented in code. A way that I’ve seen some beginners cope with this confusion is by putting in Null else statements (else statements that are just placeholders) and I am against this for 2 reasons:

Here’s an example of something a student sent me that was along those lines.

As you can see there is no functionality gained from this type of code.

Scope
Scope is essentially the “lifespan” of a variable. When a variable is declared within a specific scope it “dies” (is destroyed) with that scope. This is useful and dangerous at the same time. Scopes will become more important when we get into loops. Below is a short example showing a variable declared in a scope and being unavailable outside of the scope:

Boolean Comparison Operators

• == (Equal to)
• != (Not Equal To)
• ! (Not (typically used with bool variables))
• > (Greater Than)
• < (Less than)
• >= (Greater than / Equal to)
• <= (Less Than / Equal to)
• || (Or)
• && (And)

Please note, the listing above is not a complete list of operators, but it will encompass the scope of what we will be learning in this course. There are other operators called “Bitwise operators” that you can read about if you choose, though you will likely not need to use them for quite some time.