教c语言的书中都不建议用goto语句,但是有一部分同学还是觉得可以用,我觉得是可以用,但是代码是要给别人看的,别人看到goto语句可不好受,最好还是换成这种方法。

  

 

goto语句:

tryagain:  
    int res = doSomething();  

    //......  

    if (res < 0) {  
        goto tryagain;  
    }  
    else{  
        doSomething2();  
    } 

 

 替代方法,用do{} while(0)替代:

do{
    int res = doSomething();

    //......

    if (res < 0) {
        continue;
    }
    else{
        doSomething2();
    }
}while(0);

 

 

还有这种goto:

    int res = doSomething();

    //......

    if (res < 0) {
        goto errorOccur;
    }
    else{
        doSomething2();
    }

errorOccur:
    doThing();

 

 换成这种:

do{
    int res = doSomething();

    //......

    if (res < 0) {
        break;
    }
    else{
        doSomething2();
    }
}while(0);

doThing();

 

为什么博客园没有C语言的版块???

posted on 2010-09-26 11:02  afa2010  阅读(2629)  评论(0)    收藏  举报