Moving and copying a value
brainfuck can only move a value by counting it across, one unit at a time. Copying needs a third cell.
●○○ easy
The idea
A tape language has no "copy" command. To move a value from one cell to the next, take one away here and add one there, until here is 0, with [->+<].
Read the story
Moving empties the source. To copy, move the value into two cells at once, then move one of them back.
Step by step in brainfuck
Cell 0 holds 5.
Move 5 one cell right
Cell 0 holds 5. Each pass of [->+<] takes 1 from cell 0 and adds 1 to cell 1. After five passes cell 1 holds 5. Adding 48 prints the digit.
Expected output
5
Output
Copy the input
Read a byte into cell 0. [->+>+<<] moves it into cells 1 and 2. >>[-<<+>>] moves cell 2 back into cell 0. Now cells 0 and 1 both hold it, and both print.
Expected output
aa
Output
- The third cell is a temporary. Brainfuck programs keep spare cells for this.
Side by side
Stack languages copy in one step.
Stack languages copy in one step. The value is on the stack, and a command duplicates the top.
The kernel, DUP
Expected output
aa
Output
Underload, colon
: copies the top text, * joins the two copies.
Expected output
abab
Output
Befunge, colon
~ reads a character, : copies it, and , prints twice.
Expected output
aa
Output
Why it matters
In brainfuck, every loop that reads a value destroys it, so most longer programs copy first.
In brainfuck, every loop that reads a value destroys it, so most longer programs copy first. That is why brainfuck code is long; the machine has no stack to keep a copy for free. See tape, stack, queue, rewriting, 2D.