Você está na página 1de 1

50

CHAPTER 4 FLOW CONTROL

For instance, consider the situation (mentioned in the chapter introduction) in which you want to execute
code based on whether a variable, myVal, is less than 10. To do this, you need some indication of whether
the statement myVal is less than 10 is true or false that is, you need to know the Boolean result of a
comparison.
Boolean comparisons require the use of Boolean comparison operators (also known as relational operators),
which are shown in Table 4-1.
TABLE 4-1: Boolean Comparison Operators
OPERATOR

CATEGORY

EX AMPLE EXPRESSION

RESULT

==

Binary

var1=var2==var3;

var1 is assigned the value true if var2 is


equal to var3, or false otherwise.

!=

Binary

var1=var2!=var3;

var1 is assigned the value true if var2 is


not equal to var3, or false otherwise.

<

Binary

var1=var2<var3;

var1 is assigned the value true if var2 is


less than var3, or false otherwise.

>

Binary

var1=var2>var3;

var1 is assigned the value true if var2 is


greater than var3, or false otherwise.

<=

Binary

var1=var2<=var3;

var1 is assigned the value true if var2


is less than or equal to var3, or false
otherwise.

>=

Binary

var1=var2>=var3;

var1 is assigned the value true if var2


is greater than or equal to var3, or false
otherwise.

In all cases in Table 4-1, var1 is a bool type variable, whereas the types of var2 and var3 may vary.
You might use operators such as these on numeric values in code:
bool isLessThan10;
isLessThan10=myVal<10;

The preceding code results in isLessThan10 being assigned the value true if myVal stores a value less
than 10, or false otherwise.
You can also use these comparison operators on other types, such as strings:
bool isKarli;
isKarli=myString=="Karli";

Here, isKarli is true only if myString stores the string "Karli".


You can also compare variables with Boolean values:
bool isTrue;
isTrue=myBool==true;

Here, however, you are limited to the use of the == and != operators.
NOTE A common code error occurs if you unintentionally assume that because
val1 < val2 is false, val1 > val2 is true. If val1 == val2, both these statements
are false.

www.it-ebooks.info
c04.indd 50

17/11/12 10:20 AM

Você também pode gostar