你好,世界!在Brainfuck

Dan*_*bes 5 brainfuck

以下代码片段来自维基百科,是标准的Hello World的序言!在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. ]
Run Code Online (Sandbox Code Playgroud)

我理解这里发生的事情的要点,但我不明白的是第3到第6行发生的事情的机制.如果+++++ +++++在值中a[0]加10 ,为什么将指针递增1并执行++*ptr7次会导致a[1]等于70?不应该a[1] = 7?似乎a[1]通过a[4]神奇地增加了十倍,我不明白为什么.

Tim*_* S. 3

这些[]字符表示循环。前面的10+秒表示循环将运行多少次。当您了解各种命令的含义以及<<<< -命令的顺序时,这一点就会变得清晰。

每次循环运行时,都会执行以下步骤:

> move the pointer 1 space to the right
+++++ ++ add 7 to the current pointer
etc 3 more times > > >
<<<< - move back to the counter and decrement
Run Code Online (Sandbox Code Playgroud)

这具有添加“7,10,3,1”10 次的效果。换句话说,如果您在运行循环时将值写入前 5 个指针位置,就像它们在数组中一样:

[10, 0, 0, 0, 0]     at first
[9, 7, 10, 3, 1]     after first run
[8, 14, 20, 6, 2]    after second
...
[0, 70, 100, 30, 10] up to this, the loop ends since the counter is 0,
                     and control continues
Run Code Online (Sandbox Code Playgroud)