Our sensor logger keeps recording nonsense and nobody noticesuntil the report is wrong. I want it to refuse a value thatwill 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.
bool the caller can test. Printing a complaint is not enough if the caller then stores the value anyway. 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.
Your requirements list and your program file, named cc-overflow-guard.