References (C++)

References may be declared using the following syntax:

[storage-class-specifiers] [cv-qualifiers] type-specifiers 
[ms-modifier] declarator [= expression];

Any valid declarator specifying a reference may be used. Unless the reference is a reference to function or array type, the following simplified syntax applies:

[storage-class-specifiers] [cv-qualifiers] type-specifiers & 
[cv-qualifiers] identifier [= expression];

References are declared using the following sequence:

1. The declaration specifiers:

  • An optional storage class specifier.

  • Optional const and/or volatile qualifiers.

  • The type specifier: the name of a type.

  • 2. The declarator:

  • An optional Microsoft specific modifier. For more information, see Microsoft-Specific Modifiers.

  • The & operator.

  • Optional const and/or volatile qualifers.

  • The identifier.

3. An optional initializer.

The more complex declarator forms for pointers to arrays and functions also apply to references to arrays and functions, see pointers and declarators.

Multiple declarators and initializers may appear in a comma-separated list following a single declaration specifier. For example:

int &i; 
int &i, &j; 

References, pointers and objects may be declared together:

int &ref, *ptr, k; 

A reference holds the address of an object, but behaves syntactically like an object.

In the following program, notice that the name of the object, Today, and the reference to the object, TodayRef, can be used identically in programs:


// references.cpp
#include <stdio.h>
struct S {
   short i;

int main() {
   S  s;   // Declare the object.
   S& SRef = s;   // Declare the reference.
   s.i = 3;

   printf_s("%d\n", s.i);
   printf_s("%d\n", SRef.i);

   SRef.i = 4;
   printf_s("%d\n", s.i);
   printf_s("%d\n", SRef.i);


Topics in this section:

See Also


Initializing References