Execute both if and else statements in C/C++ simultaneously

C++Server Side ProgrammingProgramming

In this section, we will see how to execute the if and else section simultaneously in a C or C++ code. This solution is a little bit tricky.

When the if and else are executed one after another then it is like executing statements where if-else are not present. But here we will see if they are present how to execute them one after another.

Example Code

#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;
   }
}

Output

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
....
....
....

This program will act like an infinite loop, but here the, if block and else block, are executing simultaneously. After the first check, the condition checking is not really affected on the output.

Note: Here we are using a goto statement to forcefully send the control from if block to else and else to if. But the using of the goto statement is not good. It makes difficult to trace the control flow of a program.

raja
Published on 02-Apr-2019 12:41:28
Advertisements