Home > Software design >  Why does my reference update the element array it is referencing?
Why does my reference update the element array it is referencing?

Time:10-19

Could anyone explain to me in layman's terms why my reference is updating the element array that it is referencing? I thought the whole point of a reference was to only reference a value.

#include <iostream>

int main() {

    int arr[4] = { 0,0,0,0 };
    arr[0] = 1;

    int& reference = arr[0];
    reference = 2;

    std::cout << arr[0];

}

CodePudding user response:

In layman terms, as requested:

References and pointers are basically the same thing, the main difference being that references cannot be null and simplified syntax when you work with them.

Also, array variables are also pointers. arr is a pointer to the beginning of the array, arr[1] is the pointer to the second element, it is the same thing as arr 1.

When you do int& reference = arr[0], you assign your reference to point at the first element of your array. When you then call reference = 2 it means the same as if you did arr[0]=2 or

int * pointer = arr   0;
*pointer = 2;
  • Related