工作生活

c goto语句

2019-06-30  本文已影响0人  justworld

还是在大学学过点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;
}

优点

缺点

维护困难

使用建议

疑问

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;
}
上一篇下一篇

猜你喜欢

热点阅读