The 'if' and 'else' keywords


The if-else statement is a two-way decision statement. It is written as

	if ( expression )	statement1;
	[else			statement2;]
The else portion is optional. If the expression evaluates to true (anything other than 0) then statement1 is executed. If there is an else statement and the expression evaluates to false statement2 is executed. For example
(1)
	int NumberOfUsers;
	.
	.
	if( NumberOfUsers == 25 )
        {				/* No else part */
	  printf( "There are already enough users. Try later.\n" );
	  return ERROR;
        }
	.
	.


(2)	if( a >= b )	larger = a;	/* else part is present */
	else		larger = b;
Consider this code fragment:
	if( p == 1 )
	  if( q == 2 )	r = p * 2 + q;
        else r = q * 2 + p;
Because the else part is optional, there is an ambiguity when an else is omitted from a nested if sequence. In 'C', this is resolved by associating the else with the closest previous if that does not have an else. Therefore, in the above example, the else part belongs to the if(q==2) statement. The code can be made more readable by explicitly putting parentheses in the expression, like this
	if( p == 1 )
        {
	  if( q == 2 )	r = p * 2 + q;
        }
	else r = q * 2 + p;

		OR

	if( p == 1 )
        {
	  if( q == 2 )	r = p * 2 + q;
	  else r = q * 2 + p;
        }
Because the statement in the else part can also be an if statement, a construct such as shown below is possible in 'C' to create a multiple choice construct.
	if( expression1 )
	  statement1;
	else if( expression2 )
	  statement2;
	else if( expression3 )
	  statement3;
	.
	.
	else
	  statementN;

Example:

Basic if example.

See also:


Top Master Index Keywords Functions


Martin Leslie

Vinay Kanitkar