I have just discovered a programming language, which is called Brainfuck.
My question is how to write an if-else statement in Brainfuck?
Is it done by comparing two cells? If yes, then how do I compare two cells in this program?
Thank you
You need a [x,1] structure, where x can either be 0 or something else. the shortest way to explain it is to make a loop where you know that the pointer does not end the loop where it started.
let's say those cells are named cell1 and cell2
You do operations that change the value of cell1, and cell2's value does not change.
After manipulating values, make your pointer point cell1 and then you do your alternatives.
[-]> cell1 = 0
[-]+ cell2 = 1
|manipulations that change cell1 value
|goto to cell1
[ // if cell1 != 0
[-]>[-] // both cell1 and cell2 now equal 0
if you want the loop to end and want to prevent the
next loop from starting
|do something
|goto cell1 // Make sure you point again to cell1 to exit the loop
]>[ // else
|do something else
|goto cell1 // Make sure you point again to cell1 to exit the loop
]
In this example, I use //
to mark the comments and I use |
to mark operations.
Losing track of the pointer is your worst enemy, so it might help to separate your code and to put some comments.
Now! to end up answering your question : no you don't compare two cells, you do operations that either result 0 or something else and then you check if that cell == 0.
the operations you do CAN compare two cells, but you have to make your own sequence to do so
Here's the Wikipedia page for Brainfuck where you can see a lot of simple and complex algorithm for Brainfuck, and welcome to the community :)
https://esolangs.org/wiki/Brainfuck_algorithms#if_.28x.29_.7B_code1_.7D_else_.7B_code2_.7D