编写一个C/C++程序,同时执行if-else和block语句。
null
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++程序:-
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 << "Geeks" ; } return 0; } // this code is contributed by shivanisinghss2110 |
C
#include <stdio.h> int main() { if (1) //Replace 1 with 0 and see the magic { label_1: printf ( "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: printf ( "Geeks" ); } return 0; } |
输出:
Hello Geeks
因此,if和else语句块同时执行。 另一个有趣的事实是,产出将始终保持不变 这个 相同,并且不取决于布尔条件是真还是假。
笔记 –在任何编程语言中都不鼓励使用goto语句,因为它会使跟踪程序的控制流变得困难,使程序难以理解和修改。作为程序员,我们应该避免在C/C++中使用goto语句。
本博客由 Shubham Bansal .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END