11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 4: Performing Logical Operations 49int n1 = 1;int n2 = 2;n1 < n2;It’s easy to forget which operator is “greater than” and which is “less than.”Just remember that the operator is true if the arrow points to the smaller ofthe two.You may think that n1 is greater than or less than n2; however, this ignoresthe possibility that n1 and n2 are equal. The greater-than-or-equal-to operator(=) include that bit of mathematicalnuance. They are similar to the less-than and greater-than operators,with one major exception: They include equality; the other operators don’t.The && (AND) and || (OR) can combine with the other logic operators, likethis:// true if n2 is greater than n1 but n2 smaller than n3// (this is the most common way determining that n2 is in// the range of n1 to n3, exclusive)(n1 < n2) && (n2 < n3);Storing logical valuesThe result of a logical operation can be assigned to a variable of type bool:int n1 = 1;int n2 = 2;bool b;b = (n1 == n2);This expression highlights the difference between the assignment operator =and the comparison operator ==. The expression says, “Compare the variablesn1 and n2. Store the results of this comparison in the variable b.”The assignment operators are about as low down on the precedence totempole as you can get. The equality operator is executed before the assignment.The parentheses are not required — so the following is an equally valid formof logical confusion:b = n1 == n2; // compare n1 with n2; generate a true if n1// if n1 has the same value as n2, false if not// store the result, true or false, in bWhoa. Better look at that again. Note the difference between the operators.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!