In this section, we will see how to execute both if and else parts in C or C code. This solution is a bit tricky.
When if and else are executed one after another, it is as if the statement without if-else is executed. But here we will see how to execute them sequentially if they exist.
#include <iostream> using namespace std; int main() { int x = 10; if(x > 5) { lebel_1: cout << "This is inside if statement" <<endl; goto lebel_2; }else{ lebel_2: cout << "This is inside else statement" <<endl; goto lebel_1; } }
This is inside if statement This is inside else statement This is inside if statement This is inside else statement This is inside if statement This is inside else statement This is inside if statement This is inside else statement .... .... ....
The program will act as an infinite loop, but here the if block and else block are executed at the same time. After the first check, condition checks have no real impact on the output.
Note: Here we use a goto statement to force control in the if block to be sent to else , and then else to if. But using goto statement is not good. This makes it difficult to trace a program's control flow.
The above is the detailed content of Execute if and else statements simultaneously in C/C++. For more information, please follow other related articles on the PHP Chinese website!