Selection Statements. McGraw-Hill The Complete Reference Fourth Edition
ಜಾಹಿರಾತು
ಜಾಹಿರಾತು
C h a p t e r 3 : S t a t e m e n t s
59
C99 has added a Boolean type called _Bool, but it is incompatible with C++. See Part
Two for a discussion on how to achieve compatibility between C99’s _Bool and C++’s
bool
types.
Selection Statements
C/C++ supports two types of selection statements: if and switch. In addition, the ? operator is an alternative to if in certain circumstances.
if
The general form of the if statement is if (expression) statement; else statement; where a statement may consist of a single statement, a block of statements, or nothing
(in the case of empty statements). The else clause is optional.
If expression evaluates to true (anything other than 0), the statement or block that forms the target of if is executed; otherwise, the statement or block that is the target of else will be executed, if it exists. Remember, only the code associated with if or the code associated with else executes, never both.
In C, the conditional statement controlling if must produce a scalar result. A scalar is either an integer, character, pointer, or floating-point type. In C++, it may also be of type bool. It is rare to use a floating-point number to control a conditional statement because this slows execution time considerably. (It takes several instructions to perform a floating-point operation. It takes relatively few instructions to perform an integer or character operation.)
The following program contains an example of if. The program plays a very simple version of the "guess the magic number" game. It prints the message ** Right ** when the player guesses the magic number. It generates the magic number using the standard random number generator rand( ), which returns an arbitrary number between 0 and
RAND_MAX
(which defines an integer value that is 32,767 or larger). rand( ) requires the header file stdlib.h. (A C++ program may also use the new-style header <cstdlib>.)
/* Magic number program #1. */
#include <stdio.h>
#include <stdlib.h> int main(void)
{ int magic; /* magic number */
60
C + + : T h e C o m p l e t e R e f e r e n c e int guess; /* user's guess */ magic = rand(); /* generate the magic number */ printf("Guess the magic number: "); scanf("%d", &guess); if(guess == magic) printf("** Right **");
} return 0;
Taking the magic number program further, the next version illustrates the use of the
else
statement to print a message in response to the wrong number.
/* Magic number program #2. */
#include <stdio.h>
#include <stdlib.h> int main(void)
{ int magic; /* magic number */ int guess; /* user's guess */ magic = rand(); /* generate the magic number */ printf("Guess the magic number: "); scanf("%d", &guess); if(guess == magic) printf("** Right **"); else printf("Wrong");
} return 0;
Nested ifs
A nested if is an if that is the target of another if or else. Nested ifs are very common in programming. In a nested if, an else statement always refers to the nearest if statement that is within the same block as the else and that is not already associated with an else.
For example,
C h a p t e r 3 : S t a t e m e n t s
61 if(i)
{ if(j) statement 1; if(k) statement 2; /* this if */ else statement 3; /* is associated with this else */
} else statement 4; /* associated with if(i) */
As noted, the final else is not associated with if(j) because it is not in the same block.
Rather, the final else is associated with if(i). Also, the inner else is associated with if(k), which is the nearest if.
The C language guarantees at least 15 levels of nesting. In practice, most compilers allow substantially more. More importantly, Standard C++ suggests that at least 256 levels of nested ifs be allowed in a C++ program. However, nesting beyond a few levels is seldom necessary, and excessive nesting can quickly confuse the meaning of an algorithm.
You can use a nested if to further improve the magic number program by providing the player with feedback about a wrong guess.
/* Magic number program #3. */
#include <stdio.h>
#include <stdlib.h> int main(void)
{ int magic; /* magic number */ int guess; /* user's guess */ magic = rand(); /* get a random number */ printf("Guess the magic number: "); scanf("%d", &guess); if (guess == magic) { printf("** Right **"); printf(" %d is the magic number\n", magic);
} else { printf("Wrong, "); if(guess > magic) printf("too high\n"); else printf("too low\n");
}
62
C + + : T h e C o m p l e t e R e f e r e n c e
} return 0;
The if-else-if Ladder
A common programming construct is the if-else-if ladder, sometimes called the if-else-if
staircase because of its appearance. Its general form is if (expression) statement; else if (expression) statement; else
.
.
.
if (expression) statement; else statement;
The conditions are evaluated from the top downward. As soon as a true condition is found, the statement associated with it is executed and the rest of the ladder is bypassed. If none of the conditions are true, the final else is executed. That is, if all other conditional tests fail, the last else statement is performed. If the final else is not present, no action takes place if all other conditions are false.
Although the indentation of the preceding if-else-if ladder is technically correct, it can lead to overly deep indentation. For this reason, the if-else-if ladder is generally indented like this: if (expression)
statement; else if (expression)
statement;
.
.
else if (expression)
statement;
.
else
statement;
Using an if-else-if ladder, the magic number program becomes
/* Magic number program #4. */
#include <stdio.h>
C h a p t e r 3 : S t a t e m e n t s
63
#include <stdlib.h> int main(void)
{ int magic; /* magic number */ int guess; /* user's guess */ magic = rand(); /* generate the magic number */ printf("Guess the magic number: "); scanf("%d", &guess); if(guess == magic) { printf("** Right ** "); printf("%d is the magic number", magic);
} else if(guess > magic) printf("Wrong, too high"); else printf("Wrong, too low");
} return 0;
The ? Alternative
You can use the ? operator to replace if-else statements of the general form: if(condition) expression; else expression;
However, the target of both if and else must be a single expression—not another statement.
The ? is called a ternary operator because it requires three operands. It takes the general form
Exp1 ? Exp2 : Exp3
where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined as follows: Exp1 is evaluated. If it is true, Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. For example, consider
64
C + + : T h e C o m p l e t e R e f e r e n c e x = 10; y = x>9 ? 100 : 200;
In this example, y is assigned the value 100. If x had been less than 9, y would have received the value 200. The same code written with the if-else statement would be x = 10; if(x>9) y = 100; else y = 200;
The following program uses the ? operator to square an integer value entered by the user. However, this program preserves the sign (10 squared is 100 and
−10 squared is
−100).
#include <stdio.h> int main(void)
{ int isqrd, i; printf("Enter a number: "); scanf("%d", &i); isqrd = i>0 ? i*i : -(i*i); printf("%d squared is %d", i, isqrd);
} return 0;
The use of the ? operator to replace if-else statements is not restricted to assignments only. Remember, all functions (except those declared as void) return a value. Thus, you can use one or more function calls in a ? expression. When the function's name is encountered, the function is executed so that its return value may be determined.
Therefore, you can execute one or more function calls using the ? operator by placing the calls in the expressions that form the ?'s operands. Here is an example.
#include <stdio.h> int f1(int n); int f2(void);
C h a p t e r 3 : S t a t e m e n t s
65 int main(void)
{ int t; printf("Enter a number: "); scanf("%d", &t);
/* print proper message */ t ? f1(t) + f2() : printf("zero entered.\n");
} return 0; int f1(int n)
{ printf("%d ", n); return 0;
} int f2(void)
{ printf("entered.\n"); return 0;
}
Entering a 0 in this example calls the printf( ) function and displays the message zero
entered
. If you enter any other number, both f1( ) and f2( ) execute. Note that the value of the ? expression is discarded in this example. You don't need to assign it to anything.
A word of warning: Some C++ compilers rearrange the order of evaluation of an expression in an attempt to optimize the object code. This could cause functions that form the operands of the ? operator to execute in an unintended sequence.
Using the ? operator, you can rewrite the magic number program yet again.
/* Magic number program #5. */
#include <stdio.h>
#include <stdlib.h> int main(void)
{ int magic; int guess;
66
C + + : T h e C o m p l e t e R e f e r e n c e magic = rand(); /* generate the magic number */ printf("Guess the magic number: "); scanf("%d", &guess); if(guess == magic) { printf("** Right ** "); printf("%d is the magic number", magic);
} else guess > magic ? printf("High") : printf("Low");
} return 0;
Here, the ? operator displays the proper message based on the outcome of the test
guess > magic
.
The Conditional Expression
Sometimes newcomers to C/C++ are confused by the fact that you can use any valid expression to control the if or the ? operator. That is, you are not restricted to expressions involving the relational and logical operators (as is the case in languages like BASIC or Pascal). The expression must simply evaluate to either a true or false
(zero or nonzero) value. For example, the following program reads two integers from the keyboard and displays the quotient. It uses an if statement, controlled by the second number, to avoid a divide-by-zero error.
/* Divide the first number by the second. */
#include <stdio.h> int main(void)
{ int a, b; printf("Enter two numbers: "); scanf("%d%d", &a, &b); if(b) printf("%d\n", a/b); else printf("Cannot divide by zero.\n");
} return 0;
C h a p t e r 3 : S t a t e m e n t s
67
This approach works because if b is 0, the condition controlling the if is false and the
else
executes. Otherwise, the condition is true (nonzero) and the division takes place.
One other point: Writing the if statement as shown here if(b != 0) printf("%d\n", a/b); is redundant, potentially inefficient, and is considered bad style. Since the value of b alone is sufficient to control the if, there is no need to test it against 0.
switch
C/C++ has a built-in multiple-branch selection statement, called switch, which successively tests the value of an expression against a list of integer or character constants.
When a match is found, the statements associated with that constant are executed. The general form of the switch statement is switch (expression) { case constant1:
statement sequence
break; case constant2:
statement sequence
break; case constant3:
statement sequence
break;
.
.
.
default
statement sequence
}
The expression must evaluate to a character or integer value. Floating-point expressions, for example, are not allowed. The value of expression is tested, in order, against the values of the constants specified in the case statements. When a match is found, the statement sequence associated with that case is executed until the break statement or the end of the switch statement is reached. The default statement is executed if no matches are found. The default is optional and, if it is not present, no action takes place if all matches fail.
In C, a switch can have at least 257 case statements. Standard C++ recommends that at least 16,384 case statements be supported! In practice, you will want to limit the number of case statements to a smaller amount for efficiency. Although case is a label statement, it cannot exist by itself, outside of a switch.
68
C + + : T h e C o m p l e t e R e f e r e n c e
The break statement is one of C/C++'s jump statements. You can use it in loops as well as in the switch statement (see the section "Iteration Statements"). When break is encountered in a switch, program execution "jumps" to the line of code following the
switch
statement.
There are three important things to know about the switch statement:
■
The switch differs from the if in that switch can only test for equality, whereas
if
can evaluate any type of relational or logical expression.
■
No two case constants in the same switch can have identical values. Of course, a switch statement enclosed by an outer switch may have case constants that are the same.
■
If character constants are used in the switch statement, they are automatically converted to integers.
The switch statement is often used to process keyboard commands, such as menu selection. As shown here, the function menu( ) displays a menu for a spelling-checker program and calls the proper procedures: void menu(void)
{ char ch; printf("1. Check Spelling\n"); printf("2. Correct Spelling Errors\n"); printf("3. Display Spelling Errors\n"); printf("Strike Any Other Key to Skip\n"); printf(" Enter your choice: "); ch = getchar(); /* read the selection from the keyboard */ switch(ch) { case '1': check_spelling(); break; case '2': correct_errors(); break; case '3': display_errors(); break; default :
C h a p t e r 3 : S t a t e m e n t s
69
}
} printf("No option selected");
Technically, the break statements inside the switch statement are optional. They terminate the statement sequence associated with each constant. If the break statement is omitted, execution will continue on into the next case's statements until either a break or the end of the switch is reached. For example, the following function uses the "drop through" nature of the cases to simplify the code for a device-driver input handler:
/* Process a value */ void inp_handler(int i)
{ int flag; flag = -1;
} switch(i) { case 1: /* These cases have common */ case 2: /* statement sequences. */ case 3: flag = 0; break; case 4: flag = 1; case 5: error(flag); break; default: process(i);
}
This example illustrates two aspects of switch. First, you can have case statements that have no statement sequence associated with them. When this occurs, execution simply drops through to the next case. In this example, the first three cases all execute the same statements, which are flag = 0; break;
ಡೌನ್ಲೋಡ್ ಮಾಡಿ
ಜಾಹಿರಾತು