Boolean Expressions


The portion of the if statement within parentheses is the Boolean expression, sometimes referred to as a conditional. In Listing 3.28, the Boolean expression is highlighted.

Listing 3.28. Boolean Expression

 if(input < 9) {  // Input is less than 9.            System.Console.WriteLine(                "Tictactoe has more than {0}" +                 " maximum turns.", input); } // ...

Boolean expressions appear within many control flow statements. The key characteristic is that they always evaluate to true or false. For input<9 to be allowed as a Boolean expression, it must return a bool. The compiler disallows x=42, for example, because it assigns x, returning the new value, instead of checking whether x's value is 42.

Language Constrast C++Mistakenly Using = in Place of ==

The significant feature of Boolean expressions in C# is the elimination of a common coding error that historically appeared in C/C++. In C++, Listing 3.29 is allowed.

Listing 3.29. C++, But Not C#, Allows Assignment As a Boolean Expression

if(input=9)   // COMPILE ERROR: Allowed in C++, not in C#.   System.Console.WriteLine(       "Correct, tictactoe has a maximum of 9 turns.");

Although this appears to check whether input equals 9, Chapter 1 showed that = represents the assignment operator, not a check for equality. The return from the assignment operator is the value assigned to the variablein this case, 9. However, 9 is an int, and as such it does not qualify as a Boolean expression and is not allowed by the C# compiler.


Relational and Equality Operators

Included in the previous code examples was the use of relational operators. In those examples, relational operators were used to evaluate user input. Table 3.2 lists all the relational and equality operators.

Table 3.2. Relational and Equality Operators

Operator

Description

Example

<

Less than

input<9;

>

Greater than

input>9;

<=

Less than or equal to

input<=9;

>=

Greater than or equal to

input>=9;

==

Equality operator

input==9;

!=

Inequality operator

input!=9;


In addition to determining whether a value is greater than or less than another value, operators are also required to determine equivalency. You test for equivalence by using equality operators. In C#, the syntax follows the C/C++/Java pattern with ==. For example, to determine whether input equals 9 you use input==9. The equality operator uses two equal signs to distinguish it from the assignment operator, =.

The exclamation point signifies NOT in C#, so to test for inequality you use the inequality operator, !=.

The relational and equality operators are binary operators, meaning they compare two operands. More significantly, they always return a Boolean data type. Therefore, you can assign the result of a relational operator to a bool variable, as shown in Listing 3.30.

Listing 3.30. Assigning the Result of a Relational Operator to a bool

bool result = 70 > 7;

In the tic-tac-toe program (see Appendix B), you use the equality operator to determine whether a user has quit. The Boolean expression of Listing 3.31 includes an OR (||) logical operator, which the next section discusses in detail.

Listing 3.31. Using the Equality Operator in a Boolean Expression

if (input == "" || input == "quit") {     System.Console.WriteLine("Player {0} quit!!", currentPlayer);  break; }

Logical Boolean Operators

Logical operators have Boolean operands and return a Boolean result. Logical operators allow you to combine multiple Boolean expressions to form other Boolean expressions. The logical operators are ||, &&, and ^, corresponding to OR, AND, and exclusive OR, respectively.

OR Operator (||)

In Listing 3.31, if the user enters quit or presses the Enter key without typing in a value, it is assumed that she wants to exit the program. To enable two ways for the user to resign, you use the logical OR operator, ||.

The || operator evaluates two Boolean expressions and returns a TRue value if either one of them is true (see Listing 3.32).

Listing 3.32. Using the OR Operator

if((hourOfTheDay > 23) || (hourOfTheDay < 0))  System.Console.WriteLine("The time you entered is invalid.");

Note that with the Boolean OR operator, it is not necessary to evaluate both sides of the expression. The OR operators go from left to right, so if the left portion of the expression evaluates to true, then the right portion is ignored. Therefore, if hourOfTheDay has the value 33, (hourOfTheDay > 23) will return TRue and the OR operator ignores the second half of the expression. Short-circuiting an expression also occurs with the Boolean AND operator.

And Operator (&&)

The Boolean And operator, &&, evaluates to true only if both operands evaluate to TRue. If either operand is false, the combined expression will return false.

Listing 3.33 displays that it is time for work as long as the current hour is both greater than 10 and less that 24. [2] As you saw with the OR operator, the AND operator will not always evaluate the right side of the expression. If the left operand returns false, then the overall result will be false regardless of the right operand, so the runtime ignores the right operand.

[2] The typical hours that programmers work.

Listing 3.33. Using the And Operator

if ((hourOfTheDay > 10) && (hourOfTheDay < 24))     System.Console.WriteLine(     "Hi-Ho, Hi-Ho, it's off to work we go.");

Exclusive OR Operator (^)

The caret symbol, ^, is the "exclusive OR" (XOR) operator. When applied to two Boolean operands, the XOR operator returns true only if exactly one of the operands is true, as shown in Table 3.3.

Table 3.3. Conditional Values for the XOR Operator

Left Operand

Right Operand

Result

True

True

False

True

False

True

False

True

True

False

False

False


Unlike the Boolean AND and Boolean OR operators, the Boolean XOR operator does not short-circuit: It always checks both operands, because the result cannot be determined unless the values of both operands are known.

Logical Negation Operator (!)

Sometimes called the NOT operator, the logical negation operator, !, inverts a bool data type to its opposite. This operator is a unary operator, meaning it requires only one operand. Listing 3.34 demonstrates how it works, and Output 3.16 shows the results.

Listing 3.34. Using the Logical Negation Operator

boolresult; bool valid = false; result = !valid;                                                   // Displays "result = True". System.Console.WriteLine("result = {0}", result);

Output 3.16.

result = True

To begin, valid is set to false. You then use the negation operator on valid and assign a new value to result.

Conditional Operator (?)

In place of an if statement that functionally returns a value, you can use the conditional operator instead. The conditional operator is a question mark (?), and the general format is as follows:

conditional? expression1: expression2;


The conditional operator is a ternary operator, because it has three operands: conditional, expression1, and expression2. If the conditional evaluates to TRue, then the conditional operator returns expression1. Alternatively, if the conditional evaluates to false, then it returns expression2.

Listing 3.35 is an example of how to use the conditional operator. The full listing of this program appears in Appendix B.

Listing 3.35. Conditional Operator

 public  class TicTacToe {  public static string Main()  {     // Initially set the currentPlayer to Player 1;     int currentPlayer = 1;     // ...     for (int turn = 1; turn <= 10; turn++)     {        // ...        // Switch players        currentPlayer = (currentPlayer == 2) ? 1 : 2;                             }    } }

The program swaps the current player. To do this, it checks whether the current value is 2. This is the conditional portion of the conditional statement. If the result is true, then the conditional operator returns the value 1. Otherwise, it returns 2. Unlike an if statement, the result of the conditional operator must be assigned (or passed as a parameter). It cannot appear as an entire statement on its own.

Use the conditional operator sparingly, because readability is often sacrificed and a simple if/else statement may be more appropriate.




Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net