C language basics: goto statement

        In this section, we will learn a more controversial statement goto. The goto statement can make the program jump to the specified position without any conditions, so the goto statement is also called an unconditional jump statement. Its syntax is as follows

goto label;

//other code

label:

        Among them, label is a label defined by ourselves. The defined rules are the same as the names of variables. Its position is not fixed. It can be written after the goto statement or before it. However, the goto statement can only Jumping inside a function does not allow jumping out of a function.

        Of course, many books mentioning the goto statement will remind readers that it is not recommended. However, we still recommend that readers can use the goto statement reasonably.

        We can implement a loop function like a while statement through the goto statement:

int day = 1;
loop:
if (day <= 31)
{
    printf("%d\n", day);
    day++;
    goto loop;
}

 

        The above program uses goto and if statements to implement the loop function, which is the same as the loop function implemented by while, where loop is a label (label) defined by us.

        Next, let's look at an example of the reasonable use of the goto statement. Before looking at this example, let's take a look at a common implementation of jumping out according to conditions in a double loop

int found = 0;
for (int i = 0; i < n && !found; i++)
{
        for (j = 0; j < m && !found; j++)
        {
                if (a[i] == b[j])
                {
                        found = 1;
                }
        }
}
if (found)
{
        //do something
}

        由于break;语句只能跳出当前循环,不能跳出多层嵌套循环之外,所以我们只能用found变量来做为循环嵌套中的结束条件。    

        现在我们可以使用goto来完成这个功能:

for (int i = 0; i < n; i++)
{
        for (j = 0; j < m; j++)
        {
                if (a[i] == b[j])
                {
                        goto found;
                }
        }
}
found:
        // do something

        可以看到使用了goto语句的程序明显比使用双循环通过条件跳出的简洁了。 另外还有一些关于goto语句的用法,有兴趣的读者可以请参见《合理使用goto》我们在这里所说的建议大家使用是要合理的使用,而不是滥用。goto语句可以在程序中任意的跳转到指定的标签位置,所以如果用的不好可能会破坏程序的逻辑性和安全性。


欢迎关注公众号:编程外星人

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325727464&siteId=291194637