goto statement - with caution, but you can use

Recently the use of the goto statement, because if nested too deep, so the error handling agreed, direct use of the goto statement.

For example:

 

#include <stdio.h>

int main ()
{

    /* local variable definition */

    int a = 10;

    /* do loop execution */
    if (1)
    {
        do
        {
            if ( a == 15)
            {
                /* skip the iteration */
                a = a + 1;
                goto LOOP;
            }
            printf("value of a: %d\n", a);
            a++;
        }
        while ( a < 20 );

LOOP:
        printf("aa: %d\n", a);
        printf("loop: %d\n", a);
        a  = 4;
        printf("a = %d\n", a);
    }

    return 0;

}

 

  

 

多层嵌套里踹出去,或者有选择的退到第几层,这时候用goto是没毛病的,label写的明白点就行。注意不要钻来钻去,仅用于可控层数的break和continue,跳你就跳到某层循环结尾(大continue),或者紧贴在某层循环结束之后(大break)。另外记得用RAII保护资源不要泄露。对这种场景goto是最优解,该goto你就goto,用各种其他语法来“重新实现goto”是毫无意义的,只会比goto繁琐、更不可读,而且没有收益。比如说原本一个完整的算法核心逻辑,可能就那么几十行,需要goto跳几个循环的,你给搞成状态机、搞好几个只会用一次的函数,再来几个变量传递状态,你说你干嘛呢,好好一段代码被你搞成个迷宫,就为了不写“goto”?

造成这个现象的原因是C/C艹没有控制层数的break和continue,用goto是在实现这个缺失的功能。

其他场景下一般没必要用goto。

结论分析及优缺点

goto 语句可用于跳出深嵌套循环
goto语句可以往后跳,也可以往前跳,且一直往前执行

goto只能在函数体内跳转,不能跳到函数体外的函数。即goto有局部作用域,需要在同一个栈内。 

goto 语句标号由一个有效地标识符和符号";"组成,其中,标识符的命名规则与变量名称相同,即由字母、数字和下划线组成,且第一个字符必须是字母或下划线。执行goto语句后,程序就会跳转到语句标号处,并执行其后的语句。
通常goto语句与if条件语句连用,但是,goto语句在给程序带来灵活性的同时,也会使得使程序结构层次不清,而且不易读,所以要合理运用该语句。

参考:https://www.askpure.com/course_TGESH6E1-XRQR2I14-9XPX7Q53-KDBES2UV.html

https://zhuanlan.zhihu.com/p/33780928

https://www.cnblogs.com/oxspirt/p/7485873.html

https://www.zhihu.com/question/27922046

Guess you like

Origin www.cnblogs.com/CodeWorkerLiMing/p/11670913.html