goto示例

让我们看一个在C语言中使用goto语句的简单示例。

#include <stdio.h>

int main()
{
    int num, i = 1;
    printf("Enter the number whose table you want to print?");
    scanf("%d", &num);
    
    table:
    printf("%d x %d = %d\n", num, i, num * i);
    i++;
    
    if (i <= 10)
        goto table;
}

输出:

Enter the number whose table you want to print?10
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

何时应该使用goto?

只有在需要同时使用单个语句中断多个循环时,使用goto才是可取的。考虑以下示例:

#include <stdio.h>

int main()
{
    int i, j, k;
    for (i = 0; i < 10; i++)
    {
        for (j = 0; j < 5; j++)
        {
            for (k = 0; k < 3; k++)
            {
                printf("%d %d %d\n", i, j, k);
                if (j == 3)
                {
                    goto out;
                }
            }
        }
    }
    
    out:
    printf("came out of the loop");
}
arduinoCopy code
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
0 3 0
came out of the loop

以上代码中,通过使用goto语句,我们可以在j等于3时中断多个循环。

标签: c语言, c语言教程, c语言技术, c语言学习, c语言学习教程, c语言下载, c语言开发, c语言入门教程, c语言进阶教程, c语言高级教程, c语言面试题, c语言笔试题, c语言编程思想