views:

182

answers:

3

Hi all,

I have a function like below:

void add(int&,float&,float&);

and when I call:

add(1,30,30)

it does not compile.

add(1,30.0,30.0) also does not compile.

It seems that in both cases, it gets implicitly converted to double instead of float.

So, do you suggest that it is better to re-define add as add(int&,double&,double&)? Is there any other way of passing making add(1,30,30) work other than casting 30 with float or assigning like "float x = 30 ; add(1,x,x)" ?

I used to think that the compiler will be able to detect that float is a super-set of integer and so would compile it successfully. Apparently, that is not the case.

Thanks!

A: 

The upsizing of int to float to double works, but the problem is that you aren't passing variables to add(), so inside add() it can't change them.

Either change add() so it is not passing by reference (drop the &s) or pass variables of the appropriate type.

wallyk
ajay
If it did, what would happen if add() were to reassign the constant 30? Would all subsequent uses of the constant 30 use the new value? The error is saying that you can't pass a constant by reference because changing it makes no sense.
wallyk
The type (int or float) doesn't matter here. A literal number cannot bind to a non-const reference (except with VC++ which supports this by extension). Even `void foo(int int main() {foo(10);}` wouldn't compile.
UncleBens
+4  A: 

Your function takes its parameters by reference, not by value, and you can't pass constant integer/floating-point values by non-const reference. You should either change your function to take its parameters by value, or pass actual variables instead of constants, e.g.:

int x = 1;
float y = 30, z = 30;
add(x, y, z);

You can implicitly cast an int to a float or double, but you cannot implicitly cast an int& to a float&.

Adam Rosenfield
+2  A: 

In your function declaration, you are calling for "pass-by-reference":

void add(int&,float&,float&);

but you are trying to invoke the function using constants. That's the problem.

jldupont