Forum Discussion

Ron_Kim_110696's avatar
Ron_Kim_110696
Icon for Nimbostratus rankNimbostratus
Feb 22, 2007

Using "elseif" and "if" statements

Sorry if this is a duplicate, but I could not find a post regarding this question.

 

 

Here are two examples.

 

 

Uses multiple "if":

 

http://devcentral.f5.com/wiki/default.aspx/iRules/SMTPProxy.html

 

 

Uses "elseif":

 

http://devcentral.f5.com/wiki/default.aspx/iRules/UsingIRulesToManipulateCache.html

 

 

Why does one example use multiple "if" but the other uses "elseif" ?

 

 

It's not clear to me when to use "if" or "elseif".

 

 

Thank you.

2 Replies

  • Multiple consecutive "if" statements are treated as separate conditional statements. So each statement will be evaluated and if the condition test is non-zero, then the containing code block will be executed. An "elseif" and "else" are part of a "if" block and are only evaluated and subsequently processed if a previous condition has a non-zero value. In the examples you cited, the first could easily have used a single if with elseif's and that would have likely been more efficient as all "if" tests would not necessarily need to be executed.

     

     

    So, for a general rule of thumb. If your test is "if this do this, or that do that" then use a single if statement with elseif's and an else. If your test is "if this do this, if that do that", then use multiple if statements.

     

     

    Make sense? It's really just a question of how you want the logical flow of your code to go.

     

     

    -Joe