Back to Challenge Set 22

Code Challenge: Overflow Guard

Difficulty  

divider

The Brief

What they asked for
Our sensor logger keeps recording nonsense and nobody notices
until the report is wrong. I want it to refuse a value that
will not fit, and say so, instead of quietly storing garbage.

Write your requirements list before you write any code. Input, calculate, output, and anything you had to decide for yourself.


Notes

  • The largest value n bits can hold is one less than 2 to the n. Calculate it with a loop; do not type 255.
  • The number of bits is a parameter. The same method has to work for 8 bits and 16.
  • Reject anything below zero as well. Say in your requirements list what you decided about negatives, and why.
  • Write a method that returns a bool the caller can test. Printing a complaint is not enough if the caller then stores the value anyway.
  • This is Activity 2.16's overflow, caught instead of suffered.

Sample Output

Sample Output
200 stored in 8 bits
255 stored in 8 bits
256 does not fit in 8 bits (max 255)
1000 does not fit in 8 bits (max 255)
-3 does not fit in 8 bits (max 255)
with 16 bits:
200 stored in 16 bits
255 stored in 16 bits
256 stored in 16 bits
1000 stored in 16 bits
-3 does not fit in 16 bits (max 65535)

Widening to 16 bits rescues three of the five, and not the negative one. A negative reading is a different kind of wrong, and no number of bits fixes it. That difference belongs in your requirements list.


Submit

Your requirements list and your program file, named cc-overflow-guard.

Commence Challenge