Goto statement in C

05 min read

Goto statements are used to make unconditional jumps. Without testing any condition, the control can be transferred from one point to another point in the program. The use of goto is highly discouraged in a powerful structured programming language like C.

Syntax:

Backward:                                                   

label:                                                               
Statements                               
goto label     

(or)                                            

Forward:
goto label
statements
label:

The label can be named according to the user's wish provided it follows the naming rules.

Example:  Read n letters containing both uppercase and lowercase letters. Write out the letters with uppercase and lowercase letters reversed, but all other characters intact.

int main( )
{
char c;
int n=0,count=0;
printf("Enter the number of characters:");
scanf("%d",&n);
repeat:    // here repeat is the label or name of the location where
printf("Enter a character:"); the goto statement can transfer the control to.
c=getchar( );
if(isupper(c))
c=tolower(c);
else
c=toupper(c);
putchar(c);
fflush(stdin);
count++;
if(count<n)
goto repeat;
getch( );
return 0;
}

 

The number of characters to be converted is got from the user in the variable n. Then a character is read and converted to its reverse case. After this, the count variable which is initially zero is incremented and checked whether it is less than n. If so, the above-said operations have to be repeated (reading a char, converting it and displaying). Hence, the point where the reading starts is given a name or label(repeat) and the control is transferred to that point again and again as long as the count is less than n.

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error