c goto语句

作者: justworld | 来源:发表于2019-06-30 21:59 被阅读0次

    还是在大学学过点c语言,到现在基本忘光了。最近在看python源码时,goto看得有点头疼,总结一下原因还是对goto不了解,所以这篇文章统一说下c中的goto。
    goto叫无条件转移语句,C不限制程序中使用标号的次数,但各标号不得重名。

    #include <stdio.h>
    
    int main(int argc, char const *argv[])
    {
        printf("hello,world");
        goto hello;
        while (1)
        {
            printf("h");
        }
        
        hello: printf("it's a goto");
        return 0;
    }
    

    优点

    • 可以无条件跳出多重循环,不用重复写break
    • 出错时清除资源,微软子程序有许多地方用来处理出错
    • 某些情况可增加程序的清晰度

    缺点

    维护困难

    使用建议

    • 只goto到同一函数内
    • goto起点应是函数内一段小功能的结束处,goto的目的label处应是函数内另外一段小功能的开始处
    • 不能从一段复杂的执行状态中的位置goto到另外一个位置,比如,从多重嵌套的循环判断中跳出去就是不允许的
    • 应该避免向两个方向跳转

    疑问

    goto语句是否只有一行?
    :goto语句是指调到标号处代码,不能单单理解成一行代码,程序会顺序执行后面的代码,比如下面代码会导致死循环

    #include <stdio.h>
    
    int main(int argc, char const *argv[])
    {
        printf("hello,world");
        goto hello;
        while (1)
        {
            printf("h");
        }
        
        hello: printf("it's a goto");
        printf("sdfsdfsd");
        goto hello;
        return 0;
    }
    

    同时如果没有地方用goto,代码会顺序执行。`

    #include <stdio.h>
    
    int main(int argc, char const *argv[])
    {
        printf("hello,world");
        hello: printf("it's a goto");
        printf("sdfsdfsd");
        return 0;
    }
    

    相关文章

      网友评论

        本文标题:c goto语句

        本文链接:https://www.haomeiwen.com/subject/jnhicctx.html