Show: Delphi C++
Display Preferences

and, && (C++)

From RAD Studio
Jump to: navigation, search

Go Up to Keywords, Alphabetical Listing Index


Category

Alternative Representations of Tokens (C++), Operators (C++)

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 Project > Options dialog box).

Example of and

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:

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

Using && in rvalue References

As part of the new C++11 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:

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.

See Also

Personal tools
RAD Studio 10.2 Tokyo
In other languages
Previous Versions
Assistance