Simultaneous execution of both if and else blocks
for what value of x both statements will be executed??
Only in this case (on unix-like systems):
pid_t pid;
pid = fork();
if (pid == 0){
//some code
}
else {
//some code
}
In this case both branches will be always called simultaineously (well, more or less simultaneously), but in different processes.
I know we can execute if-else together like this:
This:
if(1){
goto ELSE;
}
else{
ELSE:
}
is a wrong construct. You need to use something like this instead:
if ( condition) {
//some code here
...
}
... //some other code here
If one branch is always called, then you don't need "else".
for what value of x both statements will be executed?
There is no such value: either the value evaluates to true
(something != 0), or it evaluates to false
) (0). No other possible values exist.
I know we can execute if-else together like this: if(1){ goto ELSE; } else{ ELSE: }
That works but it isn’t depending of the value of the if
condition at all.
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
.