学会使用continue,goto语句

1、continue一般可用于重发,如果发送完成第一次返回失败,则可利用continue跳过后面的语句使其继续发送。

while(resend--)
{
    ret = send();  //0
    if(ret != 0)   //1,如果ret不等于0则继续执行send()函数,跳过第3行语句
    {
        continue; //2
    }
    
    check_crc(); //3
}

continue在循环中,表示结束本次循环,进行下次循环。                                                  

2、goto语句:表示无条件跳转到标号处执行。

goto 语句可用于跳出深嵌套循环

void main()
{
    int i, j;
 
    for ( i = 0; i < 10; i++ )
    {
        printf( "Outer loop executing. i = %d\n", i );
        for ( j = 0; j < 3; j++ )
        {
            printf( " Inner loop executing. j = %d\n", j );
            if ( i == 5 )
                goto stop;
        }
    }
    /* This message does not print: */
    printf( "Loop exited. i = %d\n", i );
    stop: printf( "Jumped to stop. i = %d\n", i );
}


goto语句可以往后跳,也可以往前跳,且一直往前执行

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

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

int main()  
{  
    int n=7;    
number2:  
    printf("hello world\n");   
    if (n==7)  
    {   
        n=8;  
        printf("n=7 start\n");  
        goto number0;  
        printf("n=7 end\n");  
    }  
    else  
    {  
        printf("n=8 start\n");  
        goto number1;  
        printf("n=8 end\n");  
    }    
  
number0:   
    printf("hi number0\n");  
    goto number2;  
number1:  
    printf("hi number1\n");  
number3:  
    printf("number3\n");   
    system("pause");  
    return 0;  
}   

注意:goto标签相当于普通语句,即使没有进入循环,不符合switch中的任意一项,程序会执行一次标签,并继续执行标签以后的语句   

猜你喜欢

转载自blog.csdn.net/a2988a/article/details/84473738
今日推荐