Using goto to Exit a Nested Loop

Loops (for, while, do..while) are used often in code?especially nested loops. Eventually, you need to exit the loop by using a “break” statement. However, if you are inside of a nested loop, “break” will only let you exit one level of a loop. To exit directly, you can use “goto” to a label and exit even from a deeply nested loop.

Example:

 for(int i = 0; i < 100; i++)    {       for(int j = 0; j < 100; j++)       {          for(int k = 0; k < 100; k++)          {             if(k == 15)                goto EXIT;          }//end k loop.       }//end j loop.    }//end i loop.    EXIT:      // Perform any operations here.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: