吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C/C++ 中的 goto 语句

C/C++ 中的 goto 语句

来源:网络 | 更新时间:2022-01-14 08:17:33
goto 语句是跳转语句,有时也称为无条件跳转语句。goto 语句可用于在函数内从任意位置跳转到任意位置。 语法
Syntax1      |   Syntax2
----------------------------
goto label;  |    label:  
.            |    .
.            |    .
.            |    .
label:       |    goto label;
在上述语法中,第一行告诉编译器转到或跳转到标记为标签的语句。这里的 label 是一个用户定义的标识符,表示目标语句。紧跟在“标签:”之后的语句是目标语句。'label:' 也可以出现在 'goto label;' 之前 上述语法中的语句。 下面是一些关于如何使用 goto 语句的 示例: 示例:
  • Type 1:在这种情况下,我们将看到类似于上面 Syntax1 所示的情况。假设我们需要编写一个程序来检查一个数字是否为偶数,并使用 goto 语句进行相应的打印。下面的程序解释了如何做到这一点:
// C program to check if a number is
// even or not using goto statement
#include <stdio.h>

// function to check even or not
void checkEvenOrNot(int num)
{
if (num % 2 == 0)
// jump to even
goto even; 
else
// jump to odd
goto odd; 

even:
printf("%d is even", num);
// return if even
return; 
odd:
printf("%d is odd", num);
}

int main() {
int num = 26;
checkEvenOrNot(num);
return 0;
}
输出:
26 is even
  • Type 2: : 在这种情况下,我们会看到类似于上面 Syntax1 所示的情况。假设我们需要编写一个程序,使用 goto 语句打印从 1 到 10 的数字。下面的程序解释了如何做到这一点。
// C program to print numbers
// from 1 to 10 using goto statement
#include <stdio.h>

// function to print numbers from 1 to 10
void printNumbers()
{
int n = 1;
label:
printf("%d ",n);
n++;
if (n <= 10)
goto label;
}

// Driver program to test above function
int main() {
printNumbers();
return 0;
}
输出:
1 2 3 4 5 6 7 8 9 10

使用 goto 语句的缺点:

  • 强烈建议不要使用 goto 语句,因为它会使程序逻辑非常复杂。
  • goto 的使用使得分析和验证程序(尤其是那些涉及循环的程序)正确性的任务变得非常困难。
  • 使用breakcontinue语句可以简单地避免使用 goto 。

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com