Say we have the following C statement:
if( cond)
if( cond)
stat
else
stat
where the 'else stat' is part of the inner if statement according to the language semantics. What would I need to do in order to make the 'else stat' be part of the outer if statement? To my knowledge, adding {}
after the then and at the end of the if statement to separate them would work. Is this correct? Is there another way of doing this?
In this case you should use the compound statement
if( cond1 )
{
if ( cond2 )
stat;
}
else
{
stat;
}
Another approach from the point of view of the C syntax but less readable and should not be used is the following
if( cond1 )
if ( cond2 )
stat;
else
; // empty statement
else
stat;
However such an approach can be used then the internal if contains another else if. For example
if( cond1 )
if ( cond2 )
stat;
else if ( cond3 )
stat;
else
; // empty statement
else
stat;
Or it can be made more readable the following way
if( cond1 )
if ( cond2 )
{
stat;
}
else
{
; // empty statement
}
else
stat;