Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass float value to function taking double as reference value

I have a function whose prototype looks like this:

void example (double &var);

But, my problem is I might require to call function with some float values as well. e.g.

float temp=10.1;

example(temp)

If I do this my code don't compile, probably because of passing float value to double reference variable.

I want to avoid writing the overloaded function for double and float.

Can someone please suggest a cleaner/better way to implement this?

Function is basically a truncate function that truncate the input given & yes the original is modified.

Thank you.

like image 782
PGupta Avatar asked Feb 22 '12 13:02

PGupta


People also ask

Can we pass float value to double in Java?

With a Float object in Java we can use Float. doubleValue() method to return double value of it.

Can every float be represented as a double?

11 Answers. Show activity on this post. Yes.

Can a float be used in a function?

Python programming language has many inbuilt libraries and functions. One among them is the float() function. With the help of the float() function, we can convert an input string or an integer value to a floating point value.

How do you pass a float value in C#?

In C#, we know that Console. ReadLine() method is used to read string from the standard output device. Then this value is converted into the float type if it is not string type by default.


2 Answers

How about a template function?

template <typename T>
void example (T &var);

The compiler will replace both float and double usages (keep in mind C++ templates are macros with type-safety)

like image 163
dario_ramos Avatar answered Sep 18 '22 23:09

dario_ramos


Passing small types by reference is not recommended. You'd better have something like double example(double var);. That will solve your problem as well.

before:

void example(double& d);

double d = ...;
example(d); // unclear if d was modified

after:

double example(double d);

double d = ...;
d = example(d);

float f = ...;
f = static_cast<float>( example(f) ); // cast required to tell the compiler to allow
                                       // the precision loss
like image 44
J.N. Avatar answered Sep 16 '22 23:09

J.N.