⏩ goto Statement in C
🔍 Short Explanation:
The goto statement allows an unconditional jump to a labeled statement within the same function. Use it cautiously as it can make code less readable and harder to maintain.
✅ Syntax
goto label;
...
label:
// code to execute
📋 Example: Exiting Nested Loops
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
goto end_loop; // jump to label
}
printf("i=%d, j=%d\\n", i, j);
}
}
end_loop:
printf("Loop exited using goto.\\n");
return 0;
}
🧠 Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
Loop exited using goto.
⚠️ Use with Caution
- Overuse can lead to “spaghetti code”
- Better to use structured control statements when possible
- Sometimes useful for breaking out of deeply nested loops
📌 Summary
The goto statement provides an unconditional jump in the flow of execution within a function. Use it sparingly and thoughtfully.
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন