Skip to content

section5_if_statement

Fábio Gaspar edited this page Jan 18, 2019 · 3 revisions

The if statement

Sometimes you want to run a block of statements only if one or more conditions are verified. You already know logical and relational operators which are useful to make those conditions into an expression. Now let's explore the if statement and its different variants.

if statement

if(expression) {
   /* statements go here */
}

This is the most basic version of the if statement. How does it work? The expression between paranthesis is evaluated as a numeric value. If it evaluates to zero, it has a falsy meaning, thus the statements between curly brackets, {...}, are not executed. Otherwise, if the expression evaluates to a value different from zero, which is a thruthy value, the statements inside the if block are executed.

Because the expression is evaluated as a numeric value, in many scenarios we can make shorter but still clean code. The following two if statements are equivalent, but the first is shorter. This is useful for more compact and clean expressions, but should be used carefuly, otherwise your code might become unreadable.

if(expression) {
	/* code goes here */
}

if(expression != 0) {
	/* code goes here */
}

if ... else

The second variant of the if statement ensures that something is done, following a reasoning like: if expressionA is true, do statementA, otherwise do statementB.

It doesn't matter if the expression evaluates to falsy or truthy value, we have the guarantee that one of the blocks of statements is executed.

if(expression) {
	statementA;
} else {
	statementB;
}

Single statement if blocks

So far we have used the if statement followed by a block of statements indicated with curly brackets, {...}. This is optional if and only if the block has a single statement. The generic example for if...else statement could be re-written as follows:

if(expression)
	statementA;
else
	statementB;

Other valid examples are:

if(expression) {
	statement1;
	statement2;
	statement3;
} else 
	statement;
if(expression)
	statement;
else {
	statement1;
	statement2;
}

Both examples illustrate examples where either the if block or the else block consist of a single statement, thus the curly brackets can be removed.

However, this is sometimes the reason for not very easy to detect bugs, more specifically when using nested if statements, which results in ambiguity.

if(n > 0)
	if(n % 2 == 0)
		printf("Positive even number");
else
	printf("Negative number");

Looking at code above, if n is -5 you probably would expect the message Negative number to be printed. In fact, nothing would be shown! Indeed, the identation here is misleading, as the else statement doesn't belong to the outter if but to the inner if. Below, is the equivalent code, more naturally indented and with the print message fixed to make sense.

if(n > 0)
	if(n % 2 == 0)
		printf("Positive even number");
	else
		printf("Negative odd number");

In general, an else statement always belongs to the closest else-less if statement. When using nested if statements, make sure you use brackets to avoid bugs, because this kind of bugs is really difficult to see with naked-eye.

if...else if...else

The last version of the if statement is the if...else if...else. This let's you test several conditions. The conditions are evaluated downwards, starting at the if statement, followed by else if statement, moving to the second else if, and so on. It stops until one of the statements evaluates to true. If no expression is true and an else statement is available, then the else body is executed.

if (expression1)
	{ ... } 
else if (expression2)
	{ ... }
else if (expression3)
	{ ... }
else /* optional */
	{ ... }

Example

A simple example that outputs the largest number introduced by the user.

#include "stdio.h"

int main()
{
	int a, b, c;
	printf("Insert three values: ");
	scanf("%d %d %d", &a, &b, &c);

	if(a > b && a > c)
	{
		printf("Max = a\n");
	}
	else if(b > a && b > c)
	{
		printf("Max = b\n");
	}
	else if(c > a && c > b)
	{
		printf("Max = c\n");
	}
}
/*
OUTPUT
Insert three values: 1 5 2
Max = b
*/

Let's see another example:

#include "stdio.h"

int main()
{
	if(0 == 1)
		printf("First if\n");
	else if (3 < 4)
		printf("Second if\n");
	else if (0 == 0)
		printf("Third if\n");

}
// OUTPUT
// Second if

The first statement, 0 == 1 is not true, the expression evaluates to the zero value. The second statement, 3 < 4 is evaluated to 1, which means the statement is true. Therefore, the printf("Second if\n") is executed. The third expression, altough is also true, its body is not executed because a previous expression was true and no further expressions are tested.