How is programming in C++ like playing chess?

Imagine you are playing a game of chess with a chess program:

Chess board

When it is your turn, the program displays the board, and allows you to make a move.
The program will not allow you to make an illegal move.
The program could display all of the legal moves you could make, given the state of the pieces on the board.

Imagine you are playing a "game" of C++ with a program.

When it is your turn (and it is always your turn, like Solitaire), the program displays a semel, and allows you to "make a move" (i.e. modify that semel).
The program will not allow you to make an illegal move (i.e. make an illegal modification to that semel).
The program could display all of the legal moves (i.e. legal modifications) you could make to that semel, given the state of the semels in the program.

The Semel Editor (TM) is that program.

Here is a finite state machine for chess:

Finite state machine for chess

The initial state is "White to move".
If White is unable to make a legal move, the game is a stalemate.
If White makes a legal move, either it is checkmate and White wins or it is not checkmate and it is Black's turn.
If Black is unable to make a legal move, the game is a stalemate.
If Black makes a legal move, either it is checkmate and Black wins or it is not checkmate and it is White's turn.

[Draws are omitted to simplify the diagram.]

Note how such a finite and compact diagram generates an infinite number of chess games.
The key word in that sentence is "generates".

How can we "generate" an infinite number of legal C++ programs?

Here is a finite state machine for C++:

Finite state machine for C++

The initial state is legal.
You make a legal move.
You make a legal move.
Lather, rinse, repeat.
Voila! You end up with a legal C++ program.

If you begin in a legal state,
and you make zero or more legal moves,
then you end up in a legal state.

You can think of this as induction:

the base case: state[0] is legal.
the inductive case: if state[n] is legal, and you make a legal move, then state[n + 1] is legal.

Wouldn't it be nice if we could do that when generating a C++ program (i.e. always have a "legal program")?

The Semel Editor (TM) can do that.

In C++, a "state" is a set of semels.

The initial state is 0 semels (i.e. the empty universe).
The initial state is legal.
If you make zero or more legal moves, then you end up in a legal state.

Note that there is no way to guarantee that the generated program does what you want it to do; there is only a way to guarantee that the generated program is a "legal program".