Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

c++ - Simultaneous execution of both if and else blocks

In C or C++

if ( x )
    statement1;
else
    statement2;

For what value of x will both statements be executed?

I know we can execute if-else together like this:

if(1){
    goto ELSE;
}
else{
    ELSE:
}

Is there any way, like a value? (Which I think is not possible. Asking because someone is arguing!)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...