QUESTION 30 · Jump Statements
Explain goto with its advantages, limitations and an example.
5 marksAnswer in brief
The goto statement transfers control directly to a labelled statement in the same function.
Syntax
goto label;
/* other statements */
label:
/* destination statement */
Example explanation
In the example, n is negative, so control jumps to the invalid label. The square calculation is skipped and Invalid input is printed. For a non-negative value within the checked range, the program prints the square and returns before reaching the invalid label. A label names a destination; it does not stop ordinary execution from reaching that statement.
Advantages
- It can move out of several nested sections to one shared exit or cleanup point.
- A carefully chosen forward jump can avoid repeating the same cleanup statements.
- It provides a direct transfer when structured alternatives would make a particular cleanup path more complex.
Limitations
- Many forward and backward jumps make the execution order difficult to understand.
- A jump may skip important initialisation or checks, leading to mistakes.
- Testing and maintenance become harder when paths are scattered across the function.
Recommended use
Prefer if, switch and loops for ordinary decisions and repetition. Use goto sparingly for a clear reason. It cannot jump into another function, and C imposes extra restrictions around variably modified types. This introductory example does not use those types. A goto is not a function call and does not arrange a return to the jumping point.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int n = -4;
if (n < 0 || n > 100) { goto invalid; }
printf("Square = %d\n", n * n);
return 0;
invalid:
puts("Invalid input");
return 1;
}
Sample input and output
This example uses values already written in the program.
Output
Invalid input