ajax333221
ajax333221

Reputation: 11764

Run code if any of the "if...else if" was executed?

I am want to run code if any of the bunch of if + else if + else if... was executed:

if(){
    ...
}else if(){
    ...
}else if(){
    ...
}
//run something if ANY of the above was executed

I could add the line that I want to execute on every if or else if, but that will be too much spam.

What I have done is the following:

temp=i;//store a copy
i=-1;//make the change

if(){
    ...
}else if(){
    ...
}else if(){
    ...
}else{
    i=temp//restore if none was executed
}

The above will apply the change regardless of anything, and undo this change with an else. This works fine, but I am really worried about the readability of this code

Are there other more readable alternatives that I am missing?

Upvotes: 0

Views: 140

Answers (2)

Dmytro Shevchenko
Dmytro Shevchenko

Reputation: 34611

I'm not sure why you need two variables. How about this?

var conditionMet = true;

if(){
    ...
}else if(){
    ...
}else if(){
    ...
}else{
    conditionMet = false;
}

if(conditionMet){
    ...
}

I think that for readability purpose the main thing here would be to find a really good name for the variable, depending on what it actually represents.

Upvotes: 1

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77474

Well, you can always do

any=true;
if (...) {
} else if (...) {
} else if (...) {
} else {
  any = false;
  // or: return, if you are inside a function!
}
if (any) {
  // one of the ifs was executed.
}

If you use functions to wrap this, you can also just return in the final else. That probably is the cleanest version.

Upvotes: 1

Related Questions