Search code examples
c++variablesreference

Reference Variables In C++


I need assistance in understanding why reference variables are used in C++. The reference variables points to other variables since they are an alias of other variable We are able to create

int x = 10;
int y = x;

Why do we use it? It serves the same purpose as a reference. I'm learning C++ as a beginner. Please assist in figuring out why we chose &y = x rather than y = x for the preceding solution.


Solution

  • The difference is following:

    int x = 10;
    int y = x;
    y = 5; // After this line x == 10
    
    int& z = x;
    z = 5; // After this line x == 5