What are IF statement functions?

1 answer

Answer

1213605

2026-08-16 21:25

+ Follow

A statement and a function are two separate things. An if statement is a selection statement and has the following forms in C:

if (expression) {

statement;

}

if (expression) {

statement;

} else {

statement;

}

In the first form, the statement executes only when the expression evaluates true. In the second form, the first statement executes when the expression evaluates true, otherwise the second statement executes. The second statement may be another if statement (a nested if):

if (expression) { statement;

} else if (expression) {

statement;

} else {

statement;

}

Here, the second expression is only evaluated when the first expression evaluates false. If both expressions evaluate false, the final statement executes. Note that the final else clause is optional within nested if statements.

Nested ifs can often be thinly-disguised switch statements:

if (x==0) {

f(x);

} else if (x==1) {

g(x);

} else if (x==2) {

h(x);

} else {

i(x);

}

If statements of this type are best implemented using a switch statement:

switch (x) {

case 0: f(x); break;

case 1: g(x); break;

case 2: h(x); break;

default: i(x);

}

As well as being easier to read (and maintain), execution is more efficient as the control expression (x) need only be evaluated once and execution will immediately pass to the appropriate case label (much like a goto statement). With a nested if statement, each expression has to be evaluated in turn until one of them evaluates true, or execution passes to the else clause.

Switch statements are also more flexible in that the default clause need not be the final clause and execution automatically "falls through" to the next case label until a break or return statement is encountered.

ReportLike(0)ShareFavorite

Copyright © 2026 eLLeNow.com All Rights Reserved.