Tutorial
Problem: Arithmetic operations can yield in correct
results.
When some operation results in a result which exceeds the capacity
of a data variable to hold it, the result is undefined. This is called
"overflow". Since word size can differ between machines, code which
produces correct results in one set of circumstances may fail when
re-compiled on a machine with different hardware. When this occurs, Most
C++ compilers will continue to execute with no indication that the results
are wrong. It is the programmer's responsabiity to ensure such undefined
behavior is avoided.
This program demonstrates this problem. The solution is to replace
instances of char type with safe<char>
type.
Problem: Undetected overflow
A variation of the above is when a value is incremented/decremented
beyond it's domain. This is a common problem with for loops.
Problem: Implicit conversions change data values
A simple assign or arithment expression will generally convert all
the terms to the same type. Sometimes this can silently change values. For
example, when a signed data variable contains a negative type, assigning
to a unsigned type will be permitted by any C/C++ compiler but will be
treated as large unsigned value. Most modern compilers will emit a compile
time warning when this conversion is performed. The user may then decide
to change some data types or apply a static_cast. This is
less than satisfactory for two reasons:
It may be unwield to change all the types to signed or
unsigned.
Litering one's program with static_cast
makes it more difficult to read.
We may believe that our signed type will never contain a
negative value. If we use a static_cast to suppress the
warning, we'll fail to detect a program error when it is commited.
This is aways a risk with casts.
This solution is the same as the above, Just replace instances of
the int with safe<int>.