Buisson - 2 months ago 10x
Brainfuck Question

# I don't understand the square bracket effect

I just started learning brainfuck and I'm only at the hello world example. I have a question what the square bracket are used for?

Example:

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

This is the program "hello world". I don't understand why there is [ ] I understand
`-`
and
`+`
but I read somewhere that the brace bracket is:

``````[ (opening square bracket)
while(mem[ptr]) {
] (closing square bracket)
}
``````

but even if I have this information I don't understand why there is this here.

I'm fluent in php/C/POSIX/java but here I don't understand this.

Every `[` has to be matched to another `]`
So always think of them in pairs. Here's how you reason them out. When the program encounters a `]` it checks the current cell. If the cell has a number larger than 0 in it, the program goes back to the matching `[`. If the current cell has 0 in it the program continues.
Here is a simple example: `+++[-]` this program first sets the current cell to 3 and then clears it (you will encounter the part `[-]` quite often, this is the part used to set the cell to 0, whatever its original value was). Then it encounters the first `[` and ignores it (you can think of it as just a marker). Then it executes `-` and the first cell now becomes 2. after that it encounters the `]`. The current cell has 2 in it, so since 2 is larger than 0 the program jumps back to the `[`. it does this twice more until the value in the cell becomes 0. When the cell has 0 in it and the program encounters the `]` again, it sees that the current cell has 0 in it, so instead of jumping to the `[` it lets the program continue to the right (and since this program has no more instructions after the `]`, that means that this tiny program will end)