Simultaneous execution of both if and else blocks

后端 未结 13 2347
难免孤独
难免孤独 2020-12-10 17:45

In C or C++

if ( x )
    statement1;
else
    statement2;

For what value of x will both statements be executed?

I know

13条回答
  •  没有蜡笔的小新
    2020-12-10 18:09

    If you don't mind some undefined behavior, you can do it like this in C++:

    struct J {
      jmp_buf b;
    };
    
    struct backer {
      backer(int v):did(v) { }
    
      backer(backer const& o):j(o.j),did(o.did) { 
        o.did = true; 
      }
    
      ~backer() {
        if(!did) {
          longjmp(j.b, 1);
        }
      }
    
      operator bool() {
        return !did;
      }
    
      J j;
      mutable bool did;
    };
    
    int main() {
      if(backer b = setjmp(b.j.b)) {
        std::cout << "a";
      } else {
        std::cout << "b";
      }
    }
    

    This works fine with GCC and Clang. It works by calling setjmp on the buffer in b.j.b. That buffer is kept wrapped in a class because it can be an array, and arrays can only be copied if they are wrapped in a class. backer's constructor then takes setjmp's return value and initializes did with it. In backer's destructor that flag is tested and if it's false (first return of setjmp), it jumps back and let setjmp return a non-zero value. The destructor of backer is called when one of the branches finish.

    The compiler is free to copy the backer object constructed in initializing b. If that happens, the copy constructor of it cares about setting did to true, ensuring that we jump back only one time even if the compiler didn't optimize out the backer copy during initialization.

    Thus the program prints ab.

提交回复
热议问题