goto语句是一种跳转语句,有时也称为无条件跳转语句。goto语句可用于在函数中从任意位置跳到任意位置。 语法 :
null
Syntax1 | Syntax2 ---------------------------- goto label; | label: . | . . | . . | . label: | goto label;
在上述语法中,第一行告诉编译器转到或跳转到标记为标签的语句。这里label是一个用户定义的标识符,它指示目标语句。紧跟在“label:”后面的语句是destination语句。“label:”也可以出现在“goto label;”之前上述语法中的语句。 下面是一些关于如何使用goto语句的示例: 例如:
- 类型1 :在这种情况下,我们将看到类似于上文Syntax1所示的情况。假设我们需要编写一个程序,检查一个数字是否为偶数,并使用goto语句相应地打印。下面的程序解释了如何做到这一点:
C
// 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;
}
C++
// C++ program to check if a number is
// even or not using goto statement
#include <iostream>
using
namespace
std;
// 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:
cout << num <<
" is even"
;
// return if even
return
;
odd:
cout << num <<
" is odd"
;
}
// Driver program to test above function
int
main()
{
int
num = 26;
checkEvenOrNot(num);
return
0;
}
输出:26 is even
- 类型2: :在这种情况下,我们将看到类似于上文Syntax1所示的情况。假设我们需要编写一个程序,使用goto语句打印从1到10的数字。下面的程序解释了如何做到这一点。
C
// 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;
}
C++
// C++ program to print numbers
// from 1 to 10 using goto statement
#include <iostream>
using
namespace
std;
// function to print numbers from 1 to 10
void
printNumbers()
{
int
n = 1;
label:
cout << 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语句的缺点:
本文由 严酷的阿加瓦尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END