if Statement in C

if statement is one of the basic and primitive decision making statement supported by C language. The general syntax of if statement is as follows:

if ( condition )
statement;

This flow control construct first checks the condition and if it evaluates to True then executes the statement. The condition can be any expression that evaluates to True or False. It must be recalled that any non-zero numeric value in C language is treated as True while as zero is treated as False. This means, condition can be any of the following expressions:

1. Any constant,
2. Any variable, and
3. Any expression.

However, in general Relational expressions and Logical expressions are used to test any condition. Also, the statement can be a simple statement or a compound statement. Recall that a compound statement is a set of simple statements enclosed within a pair of curly braces. The following code snippets shows various legitimate if statements.

int x, y;
x = 10;
y = 20;
/* Using Constant values */
if ( 10 )
printf(“I will be displayed\n”);
if ( 0 )
printf(“I will NOT be displayed\n”);

/* Using Variables values */
if ( x )
printf(“I will be displayed\n”);
/* Using Arithmetic Expressions */
if ( x + y )
printf(“I will be displayed\n”);
/* Using Relational Expressions */
if ( x < y )
printf(“I will be displayed\n”);
if ( x > y )
printf(“I will NOT be displayed\n”);
/* Using Logical Expressions values */
if ( x + y > 10 && y > 10)
printf(“I will be displayed\n”);
if ( x + y > 10 && 0 )
printf(“I will NOT be displayed\n”);

It should be noted that no matter whether a condition evaluates to True or False, the rest of the statements which immediately follow the construct will be executed normally. The following code snippet explains this.

if (0 )
printf(“I will NOT be displayed\n”);
printf(“I will be displayed\n”);

It is sometimes required that execution of multiple statements be controlled by the outcome of a condition. In that case, the statements are grouped into a single compound statement. The following code snippet explains how a compound statement can be used with if construct.

if ( 0 )
{
printf(“I will NOT be displayed\n”);
printf(“Me too NOT displayed\n”);
printf(“Same here, NOT displayed\n”);
}
printf(“Oh! I will be displayed\n”);