lilzz
lilzz

Reputation: 5413

Pointers and LValue Reference

I have this situation.

 case 1
    void printInt(int & i) {}

    int main () {
       int i=1;
       printInt(&i);

    }

the printInt is expecting a reference, so therefore, inside the main, I call the printInt function and supplied with the reference i. Is this correct.

then I can also do

 case 2
     int main () {
       int i=1;
        printInt(i);    // i is a lvalue, and printInt function is expecting a lvalue

}

so, are case 1 and case 2 seems like conflicting?

Upvotes: 0

Views: 304

Answers (3)

cpp
cpp

Reputation: 3801

The second case is correct. When you pass by reference a value int x to function foo(int &y) you write:

foo(x);

This is as if you said:

int &y = x;

In the first case you call

foo(&x);

which is as if you said:

int &y = &x;

This is not how a reference is defined.

Upvotes: 0

Mahesh
Mahesh

Reputation: 34625

The first case doesn't even compile because you are passing int* but the compiler expects reference to a int type.

printInt(&i);

In the above statement, you are passing the address of an integer. So, at the receiving end it should be a pointer.

Edit:

I think you are confused between pointers and references. Think of reference as an alias to a variable. An analogy to some extent would be like a short cut for an application placed on the desktop. When you click the short cut, you are actually running the executable installed in the Applications directory. So, short cut is more like an alias for running the executable of the application.

Can short cut placed for one application be used to open different application ? No. For a similar reason, references can not be reseated.

Upvotes: 2

Erbureth
Erbureth

Reputation: 3423

Case 1 is actually incorrect, it is expecting a reference-able integer, however you are supplying it with pointer-to-integer.

Upvotes: 1

Related Questions