The following code snippet is from Wikipedia, and is the preamble to what seems to be the standard Hello World! program in Brainfuck...
1. +++++ +++++ initialize counter (cell #0) to 10
2. [ use loop to set the next four cells to 70/100/30/10
3. > +++++ ++ add 7 to cell #1
4. > +++++ +++++ add 10 to cell #2
5. > +++ add 3 to cell #3
6. > + add 1 to cell #4
7. <<<< - decrement counter (cell #0)
8. ]
I understand the gist of what's going on here, but what I don't understand is the mechanics of what's happening on lines 3 through 6. If +++++ +++++
adds 10 to the value in a[0]
, why does incrementing the pointer by one and executing ++*ptr
seven times result in a[1]
equalling 70? Shouldn't a[1] = 7
? It seems like a[1]
through a[4]
are magically being increased by a factor of ten, and I don't understand why.
The
[]
characters indicate a loop. The 10+
s before it indicate how many times the loop will run. This becomes clear when you understand what the various commands mean, and the<<<< -
sequence of commands.Each time the loop runs, it executes the following steps:
This has the effect of adding "7, 10, 3, 1" 10 times. To put it another way, if you write the values at the first 5 pointer locations as you run the loop like they're in an array: