Program: Demonstrating overflow using an 8-bit value


Repeatedly asks the user to type in a value, adding this to an 8-bit total.

If the result exceeds 255 it will not be possible to store the result using only 8 bits.

Can also enter negative values and fall through the floor, through zero!

Compile on Raspberry Pi, Apple Mac, Linux PC or Windows PC. Alternatively use repl.it

Code below:

// Demonstrating overflow using addition
// Phil Gardner

#include <iostream>
#include <climits>

using namespace std;

int main()
{
    cout << "DEMONSTRATING OVERFLOW ON AN 8-BIT VALUE" << endl << endl;

    unsigned char total = 0;
    cout << "Currently storing " << int( total ) << endl;


    unsigned short increase;
    do
    {
        cout << endl << "Increase by? ";
        cin >> increase;
        if ( cin.good() )
        {
            // Add the new amount to the old total

            cout << int( total ) << " + " << increase << " stores result ";

            total = total + increase;

            cout << int( total ) << endl;
        }
        else
        {
            // Throw away the whole line of invalid characters, ready for the next input
            cin.clear();
            cin.ignore( INT_MAX, '\n' );
        }


    } while ( true );

}