Open In App

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

Write a C/C++ program that executes both if-else block statements simultaneously. 

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 
}

Hence we can conclude that only one of the block of if-else statement will execute according to the condition of Boolean expression. 

But we can change our code so that both the statements inside the if block and the else block gets executed, for the same condition.

The trick is to use goto statement which provides an unconditional jump from the ‘goto’ to a labeled statement in the same function.

Below is C/C++ program to execute both statements simultaneously:- 




#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




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

Output: 
 

Hello Geeks

Therefore both the statements of if and else block executed simultaneously. Another interesting fact can be seen that Output will always remain the same and will not depend upon whether the Boolean condition is true or false.

NOTE – Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. As a programmer, we should avoid the use of goto statement in C/C++.

This blog is contributed by Shubham Bansal.
 


Article Tags :