The If-Else statement
If-Else provides a way to instruct the computer to execute a block of code only if certain conditions have been met. The syntax of an If-Else construct is:
if (/* condition goes here */)
{
/* if the condition is non-zero (true), this code will execute */
}
else
{
/* if the condition is 0 (false), this code will execute */
}
The first block of code executes if the condition in parentheses directly after the if evaluates to non-zero (true); otherwise, the second block executes.
The else and following block of code are completely optional. If there is no need to execute code if a condition is not true, leave it out.
Also, keep in mind that an if can directly follow an else statement. While this can occasionally be useful, chaining more than two or three if-elses in this fashion is considered bad programming practice. We can get around this with the Switch-Case construct described later.
Two other general syntax notes need to be made that you will also see in other control constructs: First, note that there is no semicolon after if or else. There could be, but the block (code enclosed in { and }) takes the place of that. Second, if you only intend to execute one statement as a result of an if or else, curly braces are not needed. However, many programmers believe that inserting curly braces anyway in this case is good coding practice.
The following code sets a variable c equal to the greater of two variables a and b, or 0 if a and b are equal.
if(a > b)
{
c = a;
}
else if(b > a)
{
c = b;
}
else
{
c = 0;
}
Consider this question: why can't you just forget about else and write the code like:
if(a > b)
{
c = a;
}
if(a < b)
{
c = b;
}
if(a == b)
{
c = 0;
}
There are several answers to this. Most importantly, if your conditionals are not mutually exclusive, two cases could execute instead of only one. If the code was different and the value of a or b changes somehow (e.g.: you reset the lesser of a and b to 0 after the comparison) during one of the blocks? You could end up with multiple if statements being invoked, which is not your intent. Also, evaluating if conditionals takes processor time. If you use else to handle these situations, in the case above assuming (a > b) is non-zero (true), the program is spared the expense of evaluating additional if statements. The bottom line is that it is usually best to insert an else clause for all cases in which a conditional will not evaluate to non-zero (true).
All text is available under the terms of the GNU Free Documentation License
Source : Wikibooks |