吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C++教程 → C++ 中同时执行 if 和 else 语句

C++ 中同时执行 if 和 else 语句

来源:网络 | 更新时间:2022-02-16 07:40:53
编写一个同时执行两个 if-else 块语句的C++ 程序。 
Syntax of if-else statement in C/C++ language is:
if (Boolean expression)
{
// Statement will execute only 
// if Boolean expression is true
}
else
{
// Statement will execute only if 
// the Boolean expression is false 
}
因此,我们可以得出结论,只有一个 if-else 语句块将根据布尔表达式的条件执行。  但是我们可以更改我们的代码,以便 if 块和 else 块中的语句都针对相同的条件执行。 诀窍是使用 goto 语句,它提供从“goto”到同一函数中的标记语句的无条件跳转。 下面是同时执行这两个语句的 C/C++ 程序:- 
#include <bits/stdc++.h>
using namespace std;
int main()
{
if (1) // Replace 1 with 0 and see the magic
{
label_1: cout <<"Hello ";

// Jump to the else statement after
// executing the above statement
goto label_2;
}
else
{
// Jump to 'if block statement' if
// the Boolean condition becomes false
goto label_1;

label_2: cout <<"52cxydh";
}
return 0;
}
输出: 
Hello 52cxydh
因此 if 和 else 块的语句同时执行。另一个有趣的事实是,输出将始终保持不变,并且不取决于布尔条件是真还是假。 注意– 在任何编程语言中都强烈建议不要使用 goto 语句,因为它难以跟踪程序的控制流,使程序难以理解和修改。作为程序员,我们应该避免在 C/C++ 中使用 goto 语句。  

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

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