Skip to study material
← Question index

QUESTION 30 · Jump Statements

Explain goto with its advantages, limitations and an example.

5 marks

Answer 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

  1. It can move out of several nested sections to one shared exit or cleanup point.
  2. A carefully chosen forward jump can avoid repeating the same cleanup statements.
  3. It provides a direct transfer when structured alternatives would make a particular cleanup path more complex.

Limitations

  1. Many forward and backward jumps make the execution order difficult to understand.
  2. A jump may skip important initialisation or checks, leading to mistakes.
  3. 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

Related exam questions

Related questions in the jump statements category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • July 2021 · Q2(b) · 5 marks

    Mention the pros and cons of goto in C.

    Paper P04 · page 1

View this category in the exam question bank →