Codectionary / Developer documentation / C++

C++ Variables, Types & References

C++ is statically typed: a variable has a type such as int, double, bool, or std::string. A reference declared with & is an alias for an existing object.

Syntax

int count = 3;
std::string name = "Ada";
int& alias = count;

Breaking down the syntax

int
An integer type.
& in a declaration
Declares an lvalue reference in this example.
const
Prevents modification through a const-qualified name or reference.

How it works

A C++ variable has a type. A reference is an alias for an existing object, so assigning through it changes that object.

Object

Create a value with an initializer.

Reference

Bind an alias to that object.

Assignment

Modify the object through the alias.

Examples

A small working example

Follow the values through this example, then change one input.

#include <iostream>
int main() {
    int lessons = 3;
    int& alias = lessons;
    alias += 1;
    std::cout << lessons << "\n";
}
  1. lessons is an object storing 3.
  2. alias refers to lessons.
  3. The assignment changes lessons to 4.

Using a reference

A small, runnable example of this syntax.

#include <iostream>

int main() {
  int count = 3;
  int& alias = count;
  alias += 1;
  std::cout << count << "\n";  // 4
}

Best practices

  • Prefer const references for read-only parameters of larger objects to avoid unnecessary copies while making intent clear.
  • Keep examples small while learning, then combine the idea with a real project.

Runtime & versions

Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ISO C++ resources

When should I use this?

Use values for independent data and references when an operation should refer to an existing object.

Common mistakes

A common trap

An ordinary local reference declaration requires an initializer.

Incorrect

int& reference; // missing initializer

Corrected

int value = 3;
int& reference = value;

Compare approaches

  • Value copy: A separate value that can change independently.
  • Reference: An alias that must not outlive its referent.

Explore deeper

Lifetime matters

A reference does not own the object it names. Never return a reference to an ordinary local variable that is destroyed when the function returns.

Specifications & further reading