Logical operators

From ZCWiki

Jump to: navigation, search

Logical operators operate on boolean (that is, true or false) values and expressions.

Contents

[edit] Syntax and Operation

[edit] Logical AND

The logical AND operator && returns a true result only if both of its operands are true. Syntax is as follows.

bool A = true;
bool B = false;
bool C;

C = A && B;

In the example above, C will be false, since B is false; both A and B must be true for C to be true.

[edit] Logical OR

The logical OR operator || returns a true result if either of its operands are true. Syntax is as follows.

bool A = true;
bool B = false;
bool C;

C = A || B;

In the example above, C will be true since A is true; either A or B must be true for C to be true, and both A and B must be false for C to be false.

[edit] Usage and Additional Examples

Note that relational operators, when used in an expression, produce a boolean result. For instance, the relational expression "X > 10" will return true if X is greater than 10, and false otherwise. You can therefore use logical operators with relational expressions, such as follows:

if ((X > 10) && (Y > 20)) {
  // do something here...
}

The statements in the if block above would only be executed if X is greater than 10 and Y is greater than 20.

If you want to check the same variable for a range of conditions - for example, if you want to check if X is greater than 10 but less than 20 - you must completely write out the necessary relational expressions. Consider the following examples.

// See if X is between 10 and 20 (inclusive).
if ((X >= 10) && (X <= 20)) {
  //...then X is between 10 and 20 inclusive.
}
// See if X is either 1 or 9.
if ((X == 1) || (X == 9)) {
  //...then X is 1 or 9.
}

You cannot take the following shortcut:

// This may or may not give you the proper result.
// It may not even compile.
// DON'T DO THIS!
if (X == 1 || 9){
  //...not really sure...
}
Personal tools