If Statement Example
Previous Topic  Next Topic 

An if_statement can either have an else clause or just have the if clause without an else.     Both of the following statements are valid:



if(i == 10)

    applog("Woohoo! i equals 10");

else

    applog("Doh! i does not equal 10");

endif



if(i == 10)

    applog("Woohoo! i equals 10");

endif




Any expression can be used for the conditional expression and the statement_block for the if clause will be executed if this expression evaluates to a non zero value.   For example all of the following are valid:



// this will alway be true

if(1)

   applog("You will always see this")

endif


// this will always be true unless a==1

if(a-1)

   applog("If you see this then a isn't 1");

endif


// this will always be true - but might be a BUG!

if(a=3)

   applog("You will always see this - but did you want to?")

endif



The last example shows that an assignment expression is a prefectly valid expression for a conditional statement but is also a common cause of bugs in applications since what is usually meant is:


// This is what was probably meant.

if(a==3)

   applog("if you see this then a must be 3");

endif


To prevent this kind of bug it might be better to use the TE style comparison operator eq.   For example:


if(a eq 3)

   applog("if you see this then a must be 3");

endif


(see More on Operators)