Goto considered useful

March 24, 2024

Aside from the usual error handling in C, gotos can be convenient for the first pass on some programs. I’ve found them quite useful for writing simple parsers of sequences of things. Consider for example parsing initializers for a struct literal,

a = { x = 5, y = 5  };
b = { x = 5, y = 5, };	// Allow trailing commas

This can be built up quite naturally using labels and gotos.

{
	match('}');

next:
	if (current() == '}')
	{
		goto done;
	}

	parse_initializer();

	if (current() == ',')
	{
		advance();
		goto next;
	}

done:
	match('}');
}

This more or less mirrors how you would parse “by eye”. For this reason, I’ve found I’m more likely to get this correct on the first pass. The actual structure then emerges, and this can be converted to something more traditional if desired.

{
	match('{');

	while (current() != '}')
	{
		parse_initializer();

		if (current() != ',')
		{
			break;
		}

		advance();
	}

	match('}');
}

Even if the goto version is just a paper exercise, its useful for figuring out the approach for more structured programming.