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 clo
ser look. By
using the
if
instruction, you can require that
portions of your program will be carried o
ut only
if a certain condition is fulfilled:
// Simple if instruction
if (Condition) {
// The following is only carr
ied out
// if the condition is fulfill
ed.
Instruction 1;
Instruction 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 e
rror in an
if
statement is instead of the double equal s
ign to use a
single equal sign. For example, instead o
f
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 bra
ckets will
only be carried out if the condition is fulfi
lled.
Otherwise, the entire block in the curly bra
ckets will
simply be skipped.
The condition must return a truth value e
ither
true
or
false
. Usually, two numerical values are
compared. In addition, there are relationa
l operators
that will probably be familiar to you from m
ath class:
if
INSTRUCTION 1
INSTRUCTION 2
Truth values a
re also known a
s
Boolean data t
ypes, abbreviat
ed as
bool
.
These can onl
y take the val
ues true
or false.
KNOWLEDGE BASE
24
CodeGamer manual inside english.indd 24
7/19/16 12:32 PM