user855
user855

Reputation: 19948

integer automatically converting to double but not float

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!

Upvotes: 0

Views: 2997

Answers (3)

jldupont
jldupont

Reputation: 96844

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.

Upvotes: 2

Adam Rosenfield
Adam Rosenfield

Reputation: 400672

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&.

Upvotes: 4

wallyk
wallyk

Reputation: 57804

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.

Upvotes: 0

Related Questions