Logical operators

From ZCWiki
Jump to: navigation, search

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

Syntax and Operation

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.

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.


Logical NOT

The logical NOT operator ! flips all boolean values - so ! true will return false, and ! false will return true.

bool A = true;
bool B = !A;
bool C = !(5 < 6);

In the example above, B will be true since A is false, and C will be false since '(5 < 6)' evaluates to true.

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...
}

Logical XOR

The logical XOR operator ^^ is not supported. It is possible to simulate this operator with the logical NOT ! and logical AND && operators, coupled with logical OR ||.

Example, if you wished to perform an instruction only if Link has either the first-level sword, or first-level boomerang, but not both, if a logical XOR was possibly, you would do this:

if ( Link->Item[SWORD1] ^^ Link->Item[BRANG1] )

... as this is not possible, you may instead use this expression to simulate logical XOR:

if ( (Link->Item[I_SWORD1] && !Link->Item[BRANG1]) || (!Link->Item[SWORD1] && Link->Item[BRANG1]) )

(e.g. A NOT-AND logic pattern.)