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


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.

Updated on: 30-Jul-2019

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements