Goto in Arduino

ArduinoSoftware & CodingHardware

goto is a control structure in Arduino, like in C, and it is used to transfer the program flow to another point in the program. It is highly discouraged, as many programmers agree that you can write every algorithm you want without the use of goto.

Excessive use of goto makes it very difficult to debug programs, or, in some cases, creates program flows which are impossible to debug. It is assumed that you will read further only if you absolutely have to use goto.


The syntax for using goto is −

goto label;



The following example demonstrates this −

void setup() {
   // put your setup code here, to run once:
   int x = random(5);

   Serial.print("Value of x is ");Serial.println(x);

   if (x % 2 == 0) {
      goto even_print;
   } else {
      goto odd_print;

   Serial.println("End of setup");

      Serial.println("x is even");
      Serial.println("x is odd");

void loop() {
   // put your main code here, to run repeatedly:


The Serial Monitor output is shown below. Note that I reset the Arduino a couple of times to get different values of x.

See that when x is even, "x is odd" also gets printed, because the odd_print label follows the even_print label. So, the next print statement follows the first one. This shows that even_print and odd_print are just markers; they don’t stop program execution.

The goto statement just changes the program flow using labels, but after the statements of one label are executed, the program proceeds linearly and executes the next line (odd_print statements in this case).

Also, note that "End of setup" never gets printed. This is because both the goto statements make the program flow skip that line. This illustrates that the program won’t come back to the original line once the statements within the label are executed. It moves forward linearly unless, of course, it encounters another goto statement. This example would have given you an idea why use of goto is discouraged.

Published on 31-Jul-2021 13:38:41