C Non-local Jumps 🎯

beginner
23 min

C Non-local Jumps 🎯

Welcome back! Today, we're diving into an exciting topic – C Non-local Jumps. These are some powerful tools that help you navigate your code, making it more flexible and adaptable to various scenarios. Let's get started!

Understanding Non-local Jumps 📝

Non-local jumps allow you to break out of a loop, continue with a loop, or jump to a specified location in your code from anywhere. In C, we have three types of non-local jumps:

  1. break
  2. continue
  3. goto

💡 Pro Tip:

Before we dive in, remember that non-local jumps can make your code harder to understand, so use them sparingly and with caution.

Break Statement ✅

The break statement is used to exit a loop (for, while, or do-while) prematurely. Here's a simple example:

c
#include <stdio.h> int main() { int i = 0; for (; i < 5; ++i) { printf("Loop Iteration: %d\n", i); if (i == 3) break; } printf("Break statement executed.\n"); return 0; }

In this example, we have a for loop that prints the loop iteration number. However, we use the break statement to exit the loop when i equals 3, and then print a message confirming the break statement has been executed.

Continue Statement ✅

The continue statement is used to skip the current iteration of a loop and move on to the next one. Here's an example:

c
#include <stdio.h> int main() { int i = 0; for (; i < 5; ++i) { if (i == 3) continue; printf("Loop Iteration: %d\n", i); } return 0; }

In this example, we have a for loop that prints the loop iteration number. However, we use the continue statement to skip printing the third iteration and move on to the fourth.

Goto Statement 💡

The goto statement allows you to jump directly to a labeled statement in your code. This can make your code harder to understand, so it's best to use it sparingly:

c
#include <stdio.h> main: int i = 0; loop: if (i == 5) goto end; printf("Loop Iteration: %d\n", i); i++; goto loop; end: printf("Goto statement executed.\n"); return 0;

In this example, we use the goto statement to create an infinite loop (loop) that prints the loop iteration number and then jumps back to the loop. We also use a label (main) to specify where to jump when the loop should end.

Quick Quiz
Question 1 of 1

What does the `break` statement do in C?

Quick Quiz
Question 1 of 1

What does the `continue` statement do in C?

Quick Quiz
Question 1 of 1

What does the `goto` statement do in C?