Code patternsControlEqual

Equal

Sets a flag to 1 when two cells hold the same number.

Watch it run

The form “Using up both” works on 2 cells, named “x” and “y”. Press Play, drag the step slider forwards and back, or change x and y with the sliders:

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

Two numbers are equal when their difference is zero. Subtracting is cheap (a flat loop), and "is it zero" is the one question brainfuck can ask.

So: x becomes x − y, and then a "not" (see not, and, or on flags) turns "zero" into 1 and everything else into 0.

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 playground17 characters

What it needs

Common mistakes
  • Thinking the same trick gives "less than". The difference tells you whether the numbers differ, but on wrapping cells not which one is larger: see less than.

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
Using up bothgrows with x, and with the difference4 when equal, else 7
Keeping bothgrows with x + y (about 20 per unit)8 when equal, else 11
Not equalgrows with x, and with the difference3 when equal, else 6
Table 2. Measured when this page was written.
FormValuesBitsCharactersPlain stepsOptimised steps
Using up bothx = 7; y = 7817404
Using up bothx = 7; y = 9817497
Using up bothx = 200; y = 38171,1287
Keeping bothx = 7; y = 78652628
Not equalx = 7; y = 9816486

Other forms

Keeping both

Layout: x, y, answer, scratch.

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

The form “Keeping both” works on 4 cells, named “x”, “y”, “answer” and “scratch”. Press Play, drag the step slider forwards and back, or change x and y with the sliders:

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

Not equal

x = 1 if the two differ.

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

The form “Not equal” works on 2 cells, named “x” and “y”. Press Play, drag the step slider forwards and back, or change x and y 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.