Many folks aren’t even aware that C/C++/Arduino has a goto command. It is so reviled, tutorials often skip over this.

goto continues program execution at a different place within a function.

The reason it’s considered so distasteful is that overdependence quickly leads to spaghetti code. Unlike the braces and conditionals that visually represent the structure and flow of code, goto throws that all out the window…it just goes places and is hard to follow.

The canonical use case for goto is breaking out of nested loops:

for (int a=0; a<10; a++) {
  for (int b=0; b<10; b++) {
    if (condition) goto linguini;
  }
}
linguini:
// Code continues here

The nested inner part of the loops will execute 100 times, unless some condition arises. Well okay, that’s one way out of the situation.

Keep in mind that anything that can be written with goto can (maybe should) be written without. One could add conditional tests to the a and b loops…at the expense of a few cycles. One could put the nested loops inside their own function and use return instead of goto.…at the expense of a few-bytes-larger program. Always some small expense.

Potentially, infrequently, goto could get you out of a bind, but other programmers will look upon you like the cat threw up on the rug. Extremely, extremely infrequently, I might use one, preceded by a whole apologetic paragraph in comments explaining the justification for its use. But usually I’ll avoid it and go through the extra hoops just to steer away from the whole tired argument.

This guide was first published on Aug 10, 2022. It was last updated on Sep 06, 2016.

This page (goto) was last updated on Aug 08, 2022.

Text editor powered by tinymce.