August 27, 2023

C++ Reference (&)

Posted on August 27, 2023  •  2 minutes  • 274 words

In C++, references are a way to create an alias for an existing variable. They provide an alternative name to access the same memory location as the original variable. References are often used for passing arguments to functions, especially to avoid making copies of large objects.

There are two main types of references in C++:

  1. references (also known as lvalue references)
  2. const references.

1. Reference (&)

Syntax:

type &referenceName = existingVariable;

A reference must be initialized when declared.

Changes made to the reference will directly affect the original variable it refers to.

Example

int age = 42;
int &ageRef = original;  // 'ageRef' is a reference to 'age'
ageRef = 50;             // This changes 'age' to 50

std::cout << age; // Output: 50

2. Const Reference:

Syntax:

const type &referenceName = existingVariable;

A const reference can be bound to both lvalues and rvalues (temporary values).

It is commonly used when you want to pass a value to a function without making a copy, and you want to ensure that the function doesn’t modify the original value.

Example:

void printValue(const int &value) {
    // 'value' is a const reference
    // value = 100 // not valid 
    std::cout << value;
}

int main() {
    int num = 123;
    printValue(num);  // Passing 'num' by const reference
    return 0;
}

Using const references can be beneficial because they avoid unnecessary copying of objects, and the const qualifier ensures that the referred value won’t be modified accidentally within the function.

Remember: when using references and const references, you need to be careful not to access memory that’s gone out of scope, as the original variable must still be valid.

Follow me

I work on everything coding and share developer memes