In C we use if, if...else and nested if...else or switch (descried in later part of the article) statements as conditional statements which are one-time decisions making. Check the following flow diagram which explain the code flow -
Syntax
Case 1
if(boolean_expression)
/* statement - will execute if the boolean expression is true */
/* Next Statement - will always be executed
or
if(boolean_expression)
{
/* statement or more statement - will execute if the boolean expression is true */
}
/* Next Statement - will always be executed
Case 2
if(boolean_expression)
/* statement1 - will execute if the boolean expression is true */
else
/* Statement 2 - will execute if the boolean expression is false */
OR
if(boolean_expression)
{
/* statement1 or more statements - will execute if the boolean expression is true */
}
else
{
/* Statement 2 or more statements - will execute if the boolean expression is false */
}
Nested IF
If statement inside if statement is called nested IF or compound if statement. IF can be present in the success part of the IF or else part of the IF.
Case 1
if(boolean_expression 1)
if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true along with boolean expression 1 is true */
}
else
{
/* Executes when the boolean expression 2 is false */
}
Case 2
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */
}
Switch Case Statement
Consider the following statement which is highly unreadable
if(Condition 1)
Statement 1
else
{
Statement 2
if(condition 2)
{
if(condition 3)
statement 3
else
if(condition 4)
{
statement 4
}
}
else
{
statement 5
}
}
Switch case statement is just rewriting the same in a more readable way.
switch(expression)
{
case value1 :
body1
break;
case value2 :
body2
break;
case value3 :
body3
break;
default :
default-body
break;
}
next-statement;
Sample Flow of Switch Statement