C goto statement

C goto statement

In this chapter you will learn how to create goto statements in C program. Also learn when to use Geto statement and when to never have to.
Geto statement in C program is known as jump statement.

Geto statement is used to change the general trend of C program.

goto syntax
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;

Here the label is identifier. When the program is seen in the geto statement, jump to the program's control label: jump and execute the execution of the label block.

C goto statement

How goto statement works?

Example: Geto Statement

// Sum of the maximum number 5 and the average determination.
// If the user inputs the negative number, the sum of the previous numbers and the average will be displayed.

# include <stdio.h>

int main ()
{

    const int maxInput = 5;
    int i;
    double number, average, sum = 0.0;
 
    for (i = 1; i <= maxInput; ++ i)
    {
        printf ("% d. Enter a number:", i);
        scanf ("% lf", & number);

    // When you enter the user's negative number, the control of the program will be near the jump label.
    if (number <0.0) {
       goto jump;
       }
        sum + = number; // sum = sum + number;
    }

    jump:

    average = sum / (i-1);
    printf ("Sum =% .2f \ n", sum);
    printf ("average =% .2f", average);

    return 0;
}

Output

1. Enter a number: 3
2. Enter a number: 4.3
3. Enter a number: 9.3
4. Enter a number: -2.9
Sum = 16.60
Average = 5.53
Reason for not using the geto statement
The use of goto makes the program difficult, and in many cases it may seem that there are bugs in the program. For example:

one:
for (i = 0; i <number; ++ i)
{
    test + = i;
    goto two;
}
two:
if (test> 5) {
  goto three;
}
... .. ...

However, geto statements can sometimes be useful. For example - if you want to take a break from the nett loop

Should not use goto statement?
If you think the use of goto statement makes your program easy, you can use it. Because the purpose here is to simplify the code so that your followers easily understand your code.

Post a Comment

0 Comments