Code patternsFirst movesSet a cell to zero

Set a cell to zero

Empties the cell under the pointer, whatever it held.

Watch it run

The form “Count down” works on one cell, named “x”. Press Play, drag the step slider forwards and back, or change x with the slider:

The figure needs JavaScript. The program below is the result for the example values.

The loop takes 1 from the cell and asks "is it zero?". It goes round until the answer is yes.

So the plain cost grows with the value: two steps for every unit. An optimising interpreter sees a loop that only counts its own cell down and sets the cell to zero in one step.

The code

This is the program the figure ran. It is brainfuck as it stands: copy it, or open it in the playground, where you can change it:

[-]
Open in the playground3 characters

What it needs

Common mistakes
  • Forgetting it before a "set to a constant". +++ adds 3, it does not set 3.
  • Clearing a cell that is known to be zero already. It is harmless, but it is one more step every time.
  • Using [+] on wide cells: it counts up to the top, which takes billions of plain steps on 32-bit cells.

What it costs

A plain step is one command. An optimised step is one step of an interpreter that folds runs of the same command and flat loops. Choose the values and watch the two bars; What costs what explains how cost is counted:

The figure needs JavaScript. The table below has the measured steps.

Cost as a formula, and measured
Table 1. The cost as a function of the values. Exact formulas are checked on every case they run.
FormPlain stepsOptimised steps
Count down1 + 2x1
Count up1 + 2 × (cell size − x), or 1 when x = 0the same: this loop is not folded
Three cells in a row7 + 2 × (a + b + c)4
Table 2. Measured when this page was written.
FormValuesBitsCharactersPlain stepsOptimised steps
Count downx = 08311
Count downx = 583111
Count downx = 255835111
Count upx = 583503503
Count upx = 250831313
Three cells in a rowa = 4; b = 0; c = 9813334

Other forms

Count up

Counts up until the cell wraps round to zero. Needs wrapping cells.

[+]
Open in the playground3 characters
Run this form step by step

The form “Count up” works on one cell, named “x”. Press Play, drag the step slider forwards and back, or change x with the slider:

The figure needs JavaScript. The program below is the result for the example values.

Three cells in a row

Clears a block and walks back.

[-]>[-]>[-]<<
Open in the playground13 characters
Run this form step by step

The form “Three cells in a row” works on 3 cells, named “a”, “b” and “c”. Press Play, drag the step slider forwards and back, or change a, b and c with the sliders:

The figure needs JavaScript. The program below is the result for the example values.

Where it is used

Sources

Every program on this page was run on many inputs, in plain and in optimised mode, and compared with JavaScript. The explanations are written for this page.