Syntax:
if (expression)
operator
If the expression is True, then the operator will be executed. If the expression is False, then nothing will happen.
Example:
if (a == x) temp = 3;
if (expression)
operator1
else
operator2
If the expression is True, then operator1 will be executed and control will be transferred to the operator following operator2 (which means that operator2 will not be executed).
If the expression is False, then operator2 will be executed.
The "else" part of the operator can be omitted. That is why ambiguity may arise in the nested operators with omitted "else" part. In this case, else is related to the nearest preceding operator in the same block that does not have the "else" part.
Examples:
1) The "else" part relates to the second if operator:
if(x > 1)
if (y == 2)
z = 5;
else
z = 6;
2) The "else" relates to the first if operator:
if (x > 1)
{
if (y == 2) z = 5;
}
else z = 6;
3) The nested if operators:
if (x == 'a') y = 1;
else
if (x == 'b')
{
y = 2;
z = 3;
}
else
if (x == 'c') y = 4;
else
printf("ERROR");
|