Wednesday, January 7, 2009

Execute code in both If and Else part

I a very trick question, if we ask some one how we instruct the program to execute both IF-Condition code and Else-Condition code in one IF-Else condition statement.

Like we have a condition as follows:

if (True) {
// code A
}
else {
// code B
}

Ideally any one code can be executed, if True than code A will be executed otherwise code B is executed. What if i want to execute both code A and code B?

Well, we know in C language, Visual basic and some other languages we have "goto" statement, "goto" statement is used to jump from one code line to another by passing any program flow, so we can do like this:

if ( True ) {
LABLE1:
// code A
goto LABEL2
}
else {
LABEL2:
// code B
}

What will happen if condition is True than code A is executed and in the next line we instruct it to jump to label "LABEL2" with "goto" statement, that’s it we have forced the program to work against the logical rule. That is why "goto" statement should not be used as it can violate the program rules and are difficult to debug as well.

No comments:

Post a Comment