编写一个同时执行两个 if-else 块语句的C++ 程序。
因此,我们可以得出结论,只有一个 if-else 语句块将根据布尔表达式的条件执行。
但是我们可以更改我们的代码,以便 if 块和 else 块中的语句都针对相同的条件执行。
诀窍是使用 goto 语句,它提供从“goto”到同一函数中的标记语句的无条件跳转。
下面是同时执行这两个语句的 C/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
}
#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 语句。