RAD Studio |  |

and, &&

Category

Alternative Representations of Operators and Tokens, Operators

Syntax

Description

The and operator is an alternative representation of the && operator (binary or logical AND).

If both operands have a value of true, the result has the value true. Otherwise, the result has the value false. Both operands are implicitly converted to bool and the result type is bool.

Unlike the & (bitwise AND) operator, the && operator guarantees left-to-right evaluation of the operands. If the left operand evaluates to 0 (or false), the right operand is not evaluated.

Both the and and && operators short-circuit (that is, do not evaluate the second operand if the first evaluates as false). Thus, it is both valid and safe to test for a null pointer, as in the following example:

In order to use the and operator, you need to check the Enable new operator names option (the -Vn compiler switch, available on the Compatibility page of the ProjectOptions dialog box).

Example of and

Copy Code

    bool test( int * p ) {
      return (p != 0) and (*p > 5);
    };
    }

Substituting && for and is also valid.

Overloading && or and

You can overload the && operator as well as the alternative representation, and. Keep in mind that when the operator is overloaded, the logic is not short-circuited, and the empty pointer test is not safe. Here is an example demonstrating how to overload and:

Copy Code

    struct example {   bool operator and ( const example & ) {return true;}// same as operator &&}

Using && in rvalue References

As part of the new C++0x standard, C++Builder now supports rvalue references. An rvalue reference is formed by placing an && (but not an and) after a type in a declaration, as follows:

Copy Code

    Apt a;Apt&& a_ref1 = a;

A major difference between the familiar lvalue reference and the new rvalue reference is that rvalue references can bind to a temporary (that is, an rvalue), but an lvalue reference (at least one that is not a const) cannot bind to an rvalue.

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!