# Two Guys Arguing

## subtraction

Posted in bf by youngnh on 04.18.09

in bf, subtracting one element’s value from another is dead simple. to subtract the value of y in cell 1 from the value of x in cell 0, starting from cell 0:

```>[<->-]
```

this type of subtraction is useful for dealing with numerical values, but doesn’t help much when we need to compare numbers. I’d like to be able to tell if x is greater than y. Subtraction seems to be the natural operation for this. Just subtract y from x and loop if x is positive. This, however, only works when we can be assured that y is less than or equal to x, in which case, our comparison is probably moot. Negative numbers, of course are considered boolean true, so what we really want is a separate subtraction operation that won’t make x any less than 0.

this isn’t too hard to write in C:

```while(x && y) {
x--; y--;
}
```

there is no && statement in bf, but a pair of nested whiles would do as well:

```while(x) {
while(y) {
x--; y--;
}
}
```

which very easily translates into bf:

```[>[-<-]]
```

There is a problem with this loop, though. It doesn’t have a consistent exit point. If x is greater than y, the loop will exit with the pointer at y’s location. If y is greater than x, then the loop will exit with the pointer at x’s location. To remedy this, we need to establish a fixed point to “rewind” to.

If we establish a 0 in cell 0 as our “anchor”, then put x in cell 1 and y in cell 2, after we finish subtracting y from x, we can “rewind” back to our anchor cell for a consistent starting and end point.

```>[>[-<-]]<[<]>
```