Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float return value, indicate an error

Tags:

c

My function returns a float value from an object. If the function cannot find a proper float value an error should be returned so i can deal with it properly in the code.

My question is how to return an error.

The option of adding an extra parameter and using it to set an error marker is not preferred.

I could return a magic value, is that a valid option? My float values in the program never exceed very large numbers ( never over 10^12) so returning an FLT_MAX to check an error might be an option.

Is there a better ( portable ) way?

like image 897
this Avatar asked Oct 24 '25 04:10

this


2 Answers

If you #include <math.h>, you can return NAN in case of error. This is the only float f for which f == f is FALSE.

like image 191
Oswald Avatar answered Oct 26 '25 18:10

Oswald


Returning a magic value is the only option, except for setting a global (which is even worse).

The best solution would be to modify the prototype, to something like:

bool findAFloat(float *result);

That is clear, easy to use, and rather obvious.

You could also go for:

float findAFloat(float ifNotFound);

and have the caller decide what to return if no value is found.

like image 25
unwind Avatar answered Oct 26 '25 19:10

unwind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!