difference in pass by pointer & reference

hi

What is the difference in pass by pointer and pass by reference?

As per my understanding, there is no differecne much.
If a function accepts pointer, then NULL check can be performed.
other than this i'm not able to see any big difference..



Can any one help me in this?
In most of the interview I was blocked to answer this..
Actually there isn' such thing as "pass by pointer". Pointers is just another data type like int, char and others. Like others data type there is two ways of passing it: by value and by reference.
References always points to valid data type. There is no such thing as "null reference". And using references you can actually change variables passed to you.
Look at following code and think, why isn't x changed in first time and changed in second?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

void passbyval(int* x)
{
    x = new int(2);
}

void passbyref(int* &x)
{
    x = new int(3);
}

int main()
{
    int* x = new int(1);
    std::cout << *x << std::endl;

    passbyval(x);
    std::cout << *x << std::endl;

    passbyref(x);
    std::cout << *x << std::endl;

    return 0;
}

Output:
1
1
3
Last edited on
References always points to valid data type.


I assume you didn't actually mean "type." If it's data we're talking about, though, references do not always refer to valid data.

For instance, a reference to an element of a vector will no longer refer to valid data when the vector has had enough elements added to it to force a reallocation. A reference to a local variable returned from a function is another example. The same duration issues are present for both.
Topic archived. No new replies allowed.