Monday, August 17, 2009

The if statement

The if statement is the most versatile way of writing conditional execution in C++. The if statement has the form:

if( condition1 )
{
     statement1:1;
     ...
     statement1:I;
}
else if( condition2 )
{
     statement2:1;
     ...
     statement2:J;
}
// a necessary amount of else ifs
else
{
     statementN:1;
     ...
     statementN:K;
}

When the execution reaches an if statement the first condition is evaluated first and so on until the condition that evaluates true is found. If the expression is true, the statements following the condition are executed and the execution is continued from the next statement following the if.

The else branch is executed if none of the previous conditions is true. The else if and else branches are volitional.None of the if statement branches is executed if the else is missing and none of the conditions is true.

The braces are not necessary (although recommendable) if there is only one statement in the branch.



Previous post

Next post




No comments:

Post a Comment