Friday 15 August 2014

c++ - Return error code as double -


I wonder if I get error code in two ways C:

  double getValue () {Double rate = 0; If (error 1) {return -1; } If (error 2) {return -2; } Return ret = ....; } Int main (zero) {double val = getValue (); If (-1 == val) {printf ("getValue: error1 \ n") return -1; } And if (-2 == wal) {printf ("getValue: error2 \ n"); Return -2; } ...... return 0; }  

So when the return value is> = 0 then this is the correct value that can be used for calculation. When the value is less than zero error, will i get a floating-point-comparison problem when comparing the return value with 1 or -2? Flag value is a bad idea, the flagging point flagging point is double the flaping point, even though twice Be accurate.

If you are using IEEE double precision floating point value, then value -1 and -2 exactly double S, and the comparison is well defined if you only copy double or read only the value, then there will be no "magic error" slip. In fact, traditional 2s On a system with 32 bit int s, each int is an IEEE double Teak can be displayed as a floating point value.

Now, you think that the change will not be the same as x / 3 * 3. will ruin the identity, therefore the code is very fragile : both fragile because flag values ​​are fragile, and because floating point equivalence is often delicate in behavior.

In C ++, there are several ways to do this, which are less delicate.

  Anang errorgroup {a, b, c}; Promotion: version & lt; Double, errorGode & gt; GetValue ();  

is a tag association that can hold a double or error_code . A std :: is expected is the proposal that you can see that there is a tag association with "bias" for the first value which is only valid ( std :: experimental :: optional < / Code> and boost :: variant ).

In both of these results, a type is being returned safely, where there is an error different type of the value compared to the non-error return type.

Optional solutions include including the error code separately (back in the form of value or as a parameter-to-error-code as a parameter (I call the ICU style) Double can be set to some unharmed value in that case (e.g., NaN ) instead of unpublished.

  double getValue (error_code * E);  

or

  will get error; value (double * out);  

Where Enum error_code {a = -1, b = -2} errors The code is an enumeration.


No comments:

Post a Comment