How should I handle possible negatives in my BrainF**k interpreter?

The first time you enter the loop, the current value will be 1 (because there's one + before the loop). Inside the loop, you then subtract 5 from that value (because there are 5 -s). So this program will simply not work if subtracting from 0 causes an overflow error.

So to make this program work, you'll need to use the wrapping_* family of methods to get wrap around instead of panics on overflow.


Most integer operations exist in different forms:

  • carrying_* (eg. u8::carrying_u8);
  • overflowing_* (eg. u8::overflowing_u8);
  • saturating_* (eg. u8::saturating_u8);
  • unchecked_* (eg. u8::unchecked_u8);
  • wrapping_* (eg. u8::wrapping_u8).

Each of these allow different level of control about what would happen if under- or overflow should happen. It's up to you to decide what you want your application to do in that case, and chose the relevant method.

There are also wrapper types, such as std::num::Wrapping and std::num::Saturating which give a more terse syntax if you always want the given behavior for all operations.