Reference/Dereference Operators

From RAD Studio
Jump to: navigation, search

Go Up to Unary Operators Index

Syntax

& cast-expression
* cast-expression

Remarks

The & and * operators work together to reference and dereference pointers that are passed to functions.

Referencing operator ( & )

Use the reference operator to pass the address of a pointer to a function outside of main().

The cast-expression operand must be one of the following:

  • A function designator.
  • An lvalue designating an object that is not a bit field and is not declared with a register storage class specifier.

If the operand is of type <type>, the result is of type pointer to <type>.

Some non-lvalue identifiers, such as function names and array names, are automatically converted into "pointer-to-X" types when they appear in certain contexts. The & operator can be used with such objects, but its use is redundant and therefore discouraged.

Consider the following example:

   T t1 = 1, t2 = 2;
   T *ptr = &t1;      // Initialized pointer
   *ptr = t2;           // Same effect as t1 = t2

T *ptr = &t1 is treated as

   T *ptr;
   ptr = &t1;

So it is ptr, or *ptr, that gets assigned. Once ptr has been initialized with the address &t1, it can be safely dereferenced to give the lvalue *ptr.

Indirection operator ( * )

Use the asterisk (*) in a variable expression to create pointers. Use the indirect operator in external functions to get a pointer's value that was passed by reference.

If the operand is of type pointer to function, the result is a function designator.

If the operand is a pointer to an object, the result is an lvalue designating that object.

The result of indirection is undefined if either of the following occur:

  • The cast-expression is a null pointer.
  • The cast-expression is the address of an automatic variable and execution of its block has terminated.

Note: & can also be the bitwise AND operator.

Note: * can also be the multiplication operator.

See also