Having Fun with goto

Difficulty: ★ ★ ★ ☆

Among the C language’s slender assortment of keywords you find goto. It’s a branching statement, which can be used to loop or to escape from some ugly programming knot. Regardless, you’re told early on in your C language education that you must avoid this keyword at all costs! That is, unless you want to try this month’s exercise.

As a review, the goto keyword branches program execution to a label. Labels are things you probably don’t use often in C programming, though they do appear inside a switch-case structure. The label is the only thing on a line of text. It’s an identifier (named like a variable) immediately followed by a colon:

there:

This label serves as a target for the goto statement:

goto there;

The goto statement ends with a semicolon, which is something you might forget (or use a colon instead). After encountering the above statement, program flow jumps to the there label and continues execution. It’s this aspect of goto that requires the warning: Using goto to hippity-hop around your source code makes the code difficult to read and lends itself to other unnecessary problems. The descriptive term is “spaghetti code,” which isn’t flattering. Even so, goto is a valid keyword and has never been deprecated.

Consider the following code, which demonstrates a nested loop:

2025_11_01-Exercise.c

#include <stdio.h>

int main()
{
    int a;
    char b;

    for( a=0; a<10; a++ )
    {
        for( b='A'; b<'K'; b++ )
        {
            printf("%c%d  ",b,a);
        }
        putchar('\n');
    }

    return 0;
}

Like most nested loops I can think of, this one processes a matrix, rows of numbers and letters, all neatly presented in a grid:

A0  B0  C0  D0  E0  F0  G0  H0  I0  J0  
A1  B1  C1  D1  E1  F1  G1  H1  I1  J1  
A2  B2  C2  D2  E2  F2  G2  H2  I2  J2  
A3  B3  C3  D3  E3  F3  G3  H3  I3  J3  
A4  B4  C4  D4  E4  F4  G4  H4  I4  J4  
A5  B5  C5  D5  E5  F5  G5  H5  I5  J5  
A6  B6  C6  D6  E6  F6  G6  H6  I6  J6  
A7  B7  C7  D7  E7  F7  G7  H7  I7  J7  
A8  B8  C8  D8  E8  F8  G8  H8  I8  J8  
A9  B9  C9  D9  E9  F9  G9  H9  I9  J9  

Your task for this month’s Exercise is to generate identical output by using goto statements and labels instead of nested for loops.

The difficulty level for this challenge to three out of four stars, which isn’t because the program itself is tough to code. No, the problem is that your C programming brain isn’t trained to think of goto as a way to accomplish this task. Yes, even though the solution presents as C code, it’s not an approach any C programmer would ever consider!

Have fun with this one! I know that I did. I marveled at my solution (which I’ll post in a week), not because it was anything that would win an award, but that it was entirely possible using a weirdo approach to C coding that I’ve never considered.

Leave a Reply