goto 和标记语句 (C)goto and Labeled Statements (C)

goto 语句将控制权转交给一个标签。The goto statement transfers control to a label. 给定标签必须位于同一函数中,并且只可以出现在同一函数中的一个语句前面。The given label must reside in the same function and can appear before only one statement in the same function.




goto identifier ;goto identifier ;

identifier : statementidentifier : statement

语句标签仅对 goto 语句有意义;在任何其他上下文中,在不考虑标签的情况下执行已标记的语句。A statement label is meaningful only to a goto statement; in any other context, a labeled statement is executed without regard to the label.

jump-statement 必须位于同一函数中,并且只能出现在同一函数中的一个语句前面。A jump-statement must reside in the same function and can appear before only one statement in the same function. 跟在 goto 后的 identifier 名称集具有自己的命名空间,因此这些名称不影响其他标识符。The set of identifier names following a goto has its own name space so the names do not interfere with other identifiers. 不能重新声明标签。Labels cannot be redeclared. 有关详细信息,请参阅命名空间See Name Spaces for more information.

尽可能优先使用 break、continue 和 return 语句而不是 goto 是一种好的编程风格。It is good programming style to use the break, continue, and return statement in preference to goto whenever possible. 由于 break 语句只从一层循环中退出,因此从深度嵌套的循环中退出循环可能需要使用 gotoSince the break statement only exits from one level of the loop, a goto may be necessary for exiting a loop from within a deeply nested loop.

此示例演示了 goto 语句:This example demonstrates the goto statement:

// goto.c  
#include <stdio.h>  

int main()  
    int i, j;  

    for ( i = 0; i < 10; i++ )  
        printf_s( "Outer loop executing. i = %d\n", i );  
        for ( j = 0; j < 3; j++ )  
            printf_s( " Inner loop executing. j = %d\n", j );  
            if ( i == 5 )  
                goto stop;  

    /* This message does not print: */  
    printf_s( "Loop exited. i = %d\n", i );  

    stop: printf_s( "Jumped to stop. i = %d\n", i );  

在此示例中,当 goto 等于 5 时,stop 语句将控制权转交给标记为 i 的点。In this example, a goto statement transfers control to the point labeled stop when i equals 5.

另请参阅See Also