esolang
Learn · Ideas1 language show it

If and else made from loops

brainfuck has no if. A loop that runs at most once is an if; a flag cell that the if clears gives an else.

●○○ easy · where to see it

The idea

A loop runs zero or more times. If its body always ends by clearing the cell it tests, it runs zero times or once. That is an if.

Read the story

For an else, set a flag cell to 1 before. The if body clears the flag. After it, a second loop on the flag runs only when the if did not.

Step by step in brainfuck

Now cell 0 is 0, so the first loop is skipped and the flag stays 1.

Echo a byte, or print E for empty

Expected output

x

Output


  • , reads into cell 0. >+< sets the flag in cell 1.
  • If cell 0 is not 0, [.>-<[-]] prints it, clears the flag, clears cell 0. The loop ends after one pass.
  • Then >[ … ] tests the flag. It is 0, so the else part is skipped.

The same program on empty input

Now cell 0 is 0, so the first loop is skipped and the flag stays 1. The else loop adds 64 and 4 to it, prints E (69), and clears it.

Expected output

E

Output


Side by side

READ gives −1 on empty input.

The kernel has IF and ELSE

READ gives −1 on empty input. IF pops the test.

Expected output

E

Output


Befunge turns

The test sends the cursor left at the end of input, onto v, which leads to a second line. Otherwise it goes right and prints the byte.

Expected output

E

Output


The kernel reads brainfuck’s [ as PTR LOAD IF BEGIN, an IF around a loop. See brainfuck.

Where to see it