Zasito
Zasito

Reputation: 279

Passing through reference a parameter to a function C++

Let's suppose this code:

void function(double &f){

// doing w/e here

}

then in the main function:

float v;

function(&v);

My compiler says that this isn't correct, buy I don't really get why.

On the same topic:

void function(float *&f){

// doing w/e here

}

then in the main function:

float *v;

function(v+5);

This is also incorrect for some reason, which I don't get either.

So my question is: Why are those calls incorrect?

Upvotes: 2

Views: 86

Answers (1)

David Hammen
David Hammen

Reputation: 33106

The first example isn't correct because &v is a pointer to a float. The function is expecting a reference to a double. A pointer to a float is not a reference to a double. They are incompatible types.

The second example isn't correct because v+5 is temporary. You can't pass a reference to a non-const temporary.

Upvotes: 4

Related Questions