C语言教程
C语言控制语句
C语言函数
C语言数组
C语言指针
C语言字符串
C语言数学函数
C语言结构
C语言文件处理
C预处理器

C语言goto语句

goto语句在C中被称为跳转语句。顾名思义,goto用于将程序控件转移到预定义标签。 goto语句可用于针对特定条件重复代码的某些部分。它也可以用来打破多个循环,这是使用单个break语句无法完成的。但是,现在避免使用goto了,因为它会使程序的可读性和复杂性降低。
语法:
label: 
//some part of the code; 
goto label;

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"); 
}
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
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4