Reputation: 723
I have a function where I pass an argument by reference since I expect the function to edit it. This function is called at several places and I only care about the ref value when called at a particular instance . Pseudocode:
test_fn(int a, int b, inc , int d, int e, int& ref)
{
//bunch of other functionalities
//.
//.
ref = (a*b+c)*(d+e);
}
test_fn(1,2,3,4,5,0)//everywhere that I do not care about ref
int value = 0;
test_fn(1,2,3,4,5, value)//I care about value here and would use it in the remainder of the code .
Why can I not pass a 0 directly ? I tried passing a NULL as well and that has a long int to an int conversion error.
Why is this wrong ? And what is the best way to achieve the expected outcome here?
Upvotes: 2
Views: 2706
Reputation: 27133
Consider this much simpler example:
test_fn(int& ref)
{
ref = 3;
}
int main() {
test_fn(0);
}
This is effectively trying to set 0 to 3. i.e:
int main() {
0 = 3;
}
But that's nonsense. An int &
(as opposed to a const int&
) can only accept something that is modifiable.
(As @nogeek001 points out, const int&
wouldn't allow us to modify ref anyway.)
Upvotes: 2
Reputation: 35440
As others have stated, you can't pass a literal as a reference.
What you can do is pass an address, and then check if it is NULL within the function:
test_fn(int a, int b, inc , int d, int e, int* ref)
{
int someValue = (a*b+c)*(d+e);
if ( ref )
*ref = someValue;
}
//...
test_fn(1,2,3,4,5,0);
int value = 0;
test_fn(1,2,3,4,5, &value)
Upvotes: 2
Reputation: 2985
in order to pass variable by reference it has to exist, passing 0 or NULL
means you're sending in a constant. You cannot edit the value of a constant, as it is actualy not a variable.
As for solving your problem, you probaby should use pointers to achieve that, then check if the pointer is set to 0, NULL
or if you use C++11, nullptr
Upvotes: 2
Reputation: 8494
ref is a reference not a pointer. 0 may be passed if it were, meaning a pointer to null; reference can't point to nothing and must be bound to an lvalue.
Upvotes: 0
Reputation: 6190
A regular int&
means that it needs to be assigned to a variable already; it needs to be an lvalue
.
0
is not assigned to a variable; it's a "free variable," which means that it's unattached to a label. This means that it's an rvalue
, a temporary variable that is not bound to a variable. It's denoted by int&&
.
rvalue
s can be converted to lvalue
s if you make it const int&
. It makes sense that a constant can be converted to a reference to int constant
(reading right to left).
However, that would be pointless, as you want to modify the variable; therefore, the answer is to follow your own convention and don't pass in things that are not already in "existence" and bound to a label/name, like constants or moved variables.
Upvotes: 2