Tuesday, 19 March 2013

Probably you are shocked by the title: how can both blocks be executed (with same condition in if()). You are taught that only one of them will execute at any given time, right?? Well, here I will show you that you are wrong!

First, I will show Windows method to achieve the goal. Consider the following code:

#include <algorithm>
#include <ctime>
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <setjmp.h>
 
using namespace std;
 
struct J
{
 jmp_buf buff;
};
 
struct backer
{
 J j;
 mutable bool did;
 
 backer(int v):did(v)
 { 
 }
 
 backer(backer const& o):j(o.j),did(o.did)
 { 
  o.did = true; 
 }
 
 ~backer()
 {
  if(!did)
  {
   longjmp(j.buff, 1);
  }
 }
 
 operator bool()
 {
  return !did;
 }
};
 
int main() {
  if(backer b = setjmp(b.j.buff))
  {
  cout << "IF Block executed.\n";
  }
  else
  {
  cout << "ELSE Block executed.";
  }
  _getch();
  return 0;
}


Run the above code in VS, and check the output. You will find that both strings are printed. The above code plays with the program execution stack to execute both blocks. As an exercise, check the code through the debugger to find inner working.



I will post its inner working, and LINUX solution for the same with explaination in future posts.

Join Our Mailing List Today Get Latest Updates : Click Here

1 comments: