user5585984
user5585984

Reputation:

Reference in C++

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.

Upvotes: 0

Views: 96

Answers (4)

dhke
dhke

Reputation: 15398

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.

Upvotes: 2

Santhosh Kumar
Santhosh Kumar

Reputation: 167

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

Upvotes: 1

Real Geek N
Real Geek N

Reputation: 165

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
$

Upvotes: 1

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.

Upvotes: 0

Related Questions