Home > database >  Storing reference in variable
Storing reference in variable

Time:12-14

I am new to C . Say I have the following code:

vector<int> vec; 
vec.push_back(5); 
int x = vec.at(0);

From my understanding, x now represents a reference to the value in the vector. If this is the case, then why is it that if I were to have x = 7, the value in the vector would still be 5?

I tried searching on the site for a relevant thread, but did not see any that answered the question.

CodePudding user response:

int x declares an integer. It is not a reference. In your code a copy is made of the value in the vector.

If you want a reference then you need to declare x as a reference to int:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v{42};
    int& x = v.at(0);
    x = 5;
    std::cout << v.at(0);
}

For further reading I suggest you pick a book and cppreference can be recommended very much https://en.cppreference.com/w/cpp/language/reference.

  •  Tags:  
  • c
  • Related