0

Suppose that we have these two situations?

int p = 10;
int& q = p;

and

int p = 10;
int q = p;

Are not these two situations the same? I am little confused with the purpose of references, so please explain difference in these two.

1
  • 3
    isocpp have a nice article on this. Commented Feb 1, 2016 at 8:50

4 Answers 4

2
int p = 10;
int& q = p;

In this case, q is for all practical purposes an alias for p. They share a memory location. If you modify q, you modify p. If you modify p, you modify q. q is just a different name for p.

int p = 10;
int q = p;

Here, q gets a copy of the value of p at the time when q is initialized. Afterwards, q and p are completely independent. Changing q does not affect p and changing p does not affect q.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @dhke. Good explanation.
1

In the second case, if you change the value of q it will not affect the value of p. In the first case, changing the value of q will also change the value of p and vice versa.

$ cat ref.cpp
#include <iostream>

int main () {
  int p = 10;
  int q = p;
  int s = 10;
  int& t = s;
  q = 11;
  t = 11;
  std::cout << p << std::endl;
  std::cout << q << std::endl;
  std::cout << s << std::endl;
  std::cout << t << std::endl;
  s = 12;
  std::cout << s << std::endl;
  std::cout << t << std::endl;
}

$ g++ ref.cpp
$ ./a.out
10
11
11
11
12
12
$

Comments

1

In Second case p q are two independent integers. in first case both p q will point to same location in the memory. as you asked for the purpose of references. please go through call by value & call by reference. you can understand the use of references. go through the page. http://www.tutorialspoint.com/cplusplus/cpp_function_call_by_reference.htm

Comments

0

Changing a reference will change the underlying variable. This can be useful in situations like:

int count_odd = 0;
int count_even = 0;
int i;

    ....

    // Create a reference to either count_odd or count_even.
    int& count = (i%1) ? count_odd : count_even;
    // Now update the right count;
    count++;

This is rather artificial, but it becomes more useful with rather more complicated situations.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.