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!
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:
breakcontinuegotoBefore we dive in, remember that non-local jumps can make your code harder to understand, so use them sparingly and with caution.
The break statement is used to exit a loop (for, while, or do-while) prematurely. Here's a simple example:
#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.
The continue statement is used to skip the current iteration of a loop and move on to the next one. Here's an example:
#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.
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:
#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.
What does the `break` statement do in C?
What does the `continue` statement do in C?
What does the `goto` statement do in C?