brainfuck

Why does this end up as 72 in Brainfuck?


so I started looking into Brainfuck and I found this line as a part of a "Hello World" Program:

    -[>+<-------]>-.

This line produces the output "H". If I understood it correctly, for that to happen the current 'block' needs to have the value 72 in ASCII but as of my understanding it would do the following:

So in the end it would be 36 but not 72. Where am I going wrong here?


Solution

  • It's in Until [0] equals 0 [...] subtract 7 from [0] (so 37 iterations) that you've got the mistake.

    255 divided by 7 isn't 37, it's about 36.42. After 37 iterations, the loop won't end, because the cell [0] contains -4 = 252. 252 is divisible by 7, so the loop will end after counting down through that.

    The issue you have is assuming the you're only wrapping around once. You're not counting down through 255, you're counting through 511, which divided by 7 is 73, which is then decremented to 72, as you state.


    This assumes 8-bit cell size, but it seems that that's what the code is written for anyways. (9 bits would work too, but that's not a usual implementation.)