Only under one condition:
The “if” instruction
You have already used the
if
instruction in the
program code. Now it’s time to take a closer look. By
using the
if
instruction, you can require that
portions of your program will be carried out only
if a certain condition is fulfilled:
// Simple if instruction
if (Condition) {
/
/ The following is only carried out
/
/ if the condition is fulfilled.
I
nstruction 1;
I
nstruction 2;
...
}
OPERATOR MEANING EXAMPLE
true
== equal to a == b when a is equal to b
< less than a < b when a is less than b
> greater than a > b when a is greater than b
!= unequal a != b when a is unequal to b
<= less than or equal to a <= b when a is less than or equal to b
>= greater than or equal to a >= b when a is greater than or equal to b
ATTENTION!
A common and not always easy-to-find error in an
if
statement is instead of the double equal sign to use a
single equal sign. For example, instead of
if (a == b)
the incorrect statement would be
if (a = b)
.
In the case of this
if
statement the value of
a
is
assigned the value
b
. If that value is greater than zero
(
true
), the block of text in the curly brackets is
executed.
The parts of the program in the curly brackets will
only be carried out if the condition is fulfilled.
Otherwise, the entire block in the curly brackets will
simply be skipped.
The condition must return a truth value either
true
or
false
. Usually, two numerical values are
compared. In addition, there are relational operators
that will probably be familiar to you from math class:
if
INSTRUCTION 1
INSTRUCTION 2
Truth values are also known as
Boolean data types, abbreviated as
bool
.
These can only take the values true
or false.
KNOWLEDGE BASE
CodeGamer manual inside english.indd 24 7/19/16 12:32 PM