Quote:>How does one check on overflow/underflow for the following C++ types:
>long, short, float, double, for add, subtract, multiply, divide.
> long L;
> L = 2147483647;
> // Check flag to see if it overflowed.
<other examples snipped>
define a template called SafeType<class type>
Inside the template put crackers that verify 'type' is a primitive built-in
type and not a derived type. Use 'assert' statements that check RTTI,
Now define every math operator that native scalar types support; '++', '%',
'<<', etc. Define some of these as free friend functions, so binary
operators balance properly between the left and right sides. Also give your
template a conversion operator that converts to the base type.
And inside each operator use the standard library's "traits" templates to
ensure the result of an operation did not excede the base type's limits.
Make sure to include the assignment operator.
Check the C++ literature to make sure you match the "canonical types" of
all operators. 'operator==', for example, will be 'bool operator==
(SafeType<type> const &r, SafeType<type> const &h)', not 'int operator==
(SafeType<type> &r, SafeType<type> &h)'.
Now the real decision comes.
You can either check for overflow using 'assert', or 'throw'. This was the
decision the authors of the software piloting the Ariane V faced. They
) for dissertations on the Ariane V rocket.
If you use 'assert', the statements disappear when you compile for release.
This means your debug system has to execute every possible call tree that
your program in the field might face. But your final program will be really
small and fast. If I wrote compilers I would write them like this - all we
need to test is a humongous set of files of source code - we turn on a MAKE
program and wander away while the debug version of our program tests
If you use 'throw', your release program is just a little bigger and
slower. And you must write code somewhere that '
catch's, and does something non-useless so the program recovers. You
effectively have more program control paths to test now, and every line of
this code must be "exception safe". This is the tack I would take if I was
writing the hardware controller for a vehicle, power plant or rocket.
======= http://users.deltanet.com/~tegan/home.html =======
-- Just Say No to Teamwork! --
[ about comp.lang.c++.moderated. First time posters: do this! ]