1 / 45

Flow of Control

Flow of Control. Kernighan/Ritchie: Kelley/Pohl:. Chapter 3 Chapter 4. Control Flow Statements. Normal program flow executes statements one after the other Special statements allow the programmer to change the flow of control Selection statements: if-else and switch

sabella
Télécharger la présentation

Flow of Control

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Flow of Control Kernighan/Ritchie: Kelley/Pohl: Chapter 3 Chapter 4

  2. Control Flow Statements • Normal program flow executes statements one after the other • Special statements allow the programmer to change the flow of control • Selection statements: if-else and switch • Iteration statements: while, do and for • Direct jump: goto

  3. Lecture Overview • Boolean expressions • The if statement • The switch statement • Iteration statements –for and while • The break and continue statements • The goto statement

  4. Boolean Expressions • Each of these statements (except goto) depends on a condition • Conditions normally contain one or moreof the following operators: • Relational operators: >, >=, <, <= • Equality operators: ==, != • Logical operators: &&, ||, !

  5. Boolean Expressions • Since there is no Boolean type in C, Boolean expressions evaluate to 0 or to 1 • Similarly, the condition in a control flow statement is simply tested for its numeric value – either zero or non-zero • Therefore, there is no restriction on the type of the expression in the condition

  6. Boolean Expressions – Examples

  7. Operator Precedence • When an expression contains several operators, the compiler needs to knowthe order in which to evaluate them • The order of precedence for each operator is defined in a table (see book) • Parentheses must be used when: • A different order of evaluation is desired • Operators have the same level of precedence

  8. Operator Precedence • In general, the order in which operators are evaluated, from high to low, is: • Access and Grouping: (), [], ., -> • Unary: ++, --, !, & (address), * (dereference) • Arithmetic: +, -, * (multiplication), /, % • Relational and Equality: >, >=, <, <=, ==, != • Logical: &&, || • Assignment: =, +=, -=, *=, /=, etc.

  9. Operator Precedence – Examples

  10. Operator Precedence – Examples int a = 5; float b = 3; int isSmaller; isSmaller = a < b; printf ("isSmaller : %d\n", isSmaller); printf ("a > b : %d\n", a > b); printf ("a != b + 2 : %d\n", a != b + 2); printf ("a = b == 3 : %d\n", a = b == 3); isSmaller : 0 a > b : 1 a != b + 2 : 0 a = b == 3 : 1

  11. Short-Circuited Operators • The processing of logical AND and logical OR is “short-circuited” • If the left operand is sufficient to determine the result, the right operand is not evaluated • This feature should be used with care if (count != 0 && total/count > MAX) printf ("Ratio exceeds maximum.\n");

  12. Lecture Overview • Boolean expressions • The if statement • The switch statement • Iteration statements –for and while • The break and continue statements • The goto statement

  13. The if Statement • The if statement has the following syntax: • The else clause may be dropped • Each statement may also be a compound statement (a block) if (condition) statement1; else statement2;

  14. Nested if Statements • The statement executed as a result of an if statement or else clause could be another if statement • These are called nested if statements • An else clause is matched to the last unmatched if

  15. The Dangling else Problem • Consider the following code segments – which one is properly formatted? if (a == 1) if (b == 2) printf ("***\n"); else printf ("###\n"); if (a == 1) if (b == 2) printf ("***\n"); else printf ("###\n");

  16. The Dangling else Problem • The second version is the correct one (although the compiler will accept both) • To match an else to a different if than the nearest one, we must use braces: if (number >= 0 ) { if ((number % 2) == 0) printf ("number is even."); } else printf ("number is negative.");

  17. Multi-branch if • Syntax of the multi-branch if statement: if (condition1) statement1; else if (condition2) statement2; . . . else if (condition_n) statement_n; else default_statement;

  18. Multi-branch if • The multi-branch if statement is just a list of nested if statements • However, since it is so commonly used, it is treated as if it were a new kind of selection statement • Thus, it is formatted in a way that conveys its meaning more clearly

  19. Multi-branch if– Example int balance; printf ("Please enter your balance: "); scanf ("%d", &balance); if (balance > 0) printf ("Positive balance.\n"); else if (balance < 0 && balance >= -100) printf ("Negative balance.\n"); else if (balance < -100) printf ("Balance exceeds limit.\n"); else printf ("Zero balance.\n"); Please enter your balance: 45 Positive balance.

  20. The Conditional Operator • The following programming construct is quite common: • The conditional operator providesa short-cut for the above: if (id1 > id2) larger = num1; else larger = num2; larger = (id1 > id2)? num1: num2;

  21. Lecture Overview • Boolean expressions • The if statement • The switch statement • Iteration statements –for and while • The break and continue statements • The goto statement

  22. The switch Statement • The syntax of the switch statement: switch (expression) { case value1: statement-list1 case value2: statement-list2 case value3: statement-list3 case ... default: }

  23. The switch Statement – Example • An example of a switch statement: switch (letter) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; default: errorCount++; }

  24. Intentional Fall-through • Normally, a break is used as the last statement in each case's block • If not, operation falls-through to the first statement of the next case • Missing breaks can result in hard to find bugs • If fall-through is used intentionally, it must be properly documented

  25. switch Expression Type • The type of the expression in a switch statement must be integral (or char ) • The value in the label of each case must be a constant • The implicit Boolean condition in a switch statement is equality, thus no other relational checks can be performed

  26. Lecture Overview • Boolean expressions • The if statement • The switch statement • Iteration statements –for and while • The break and continue statements • The goto statement

  27. The while Statement • The syntax of the while statement: • The syntax of the do-while statement: • statement is executed at least once while (condition) statement; do statement; while (condition)

  28. The while Statement – Example while ((c = getchar()) != EOF) { if (c == ' ') blank_cnt++; else if (c >= '0' && c <= '9') digit_cnt++; else if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') letter_cnt++; else if (c == '\n') nl_cnt++; else other_cnt++; }

  29. The Empty Statement • Wherever a statement may be used, the empty statement is also allowed • Example – skip all initial blank characters in the input stream: while ((c = getchar()) == ' ') ; /* empty statement */

  30. The for Statement • The syntax of the for statement: • A for loop is functionally equivalent to the following while loop structure: for (initialization; condition; increment) statement; initialization; while (condition) { statement; increment; }

  31. The for Statement • The initialization section cannot be used to declare a variable, only to set its value • Any or all of the three parts may be omitted, for example (infinite loop): printf ("This can take a while...\n"); for ( ; ; ) printf ("*");

  32. The Comma Operator • The comma operator has the lowest precedence of all the operators in C: • expr1 is evaluated first, and then expr2 • The value returned by this expression is the value returned by expr2 expr1, expr2

  33. The Comma Operator – Examples • Commonly used for multiple initializations: • What will be printed by this code segment? for (sum = 0, i = 1; i <= n; i++) sum += i; int a = 5, b = 3, c; a++, c = (b++, a + b); printf ("%d\n", c); 10

  34. Lecture Overview • Boolean expressions • The if statement • The switch statement • Iteration statements –for and while • The break and continue statements • The goto statement

  35. The break Statement • The break statement causes an exit from the innermost enclosing loop or switch • Example: while (1) { scanf ("%f", &x); if (x < 0.0) break; /* exit loop if x is negative */ printf ("%f\n", sqrt(x)); } /* break jumps to here */

  36. The continue Statement • The continue statement causes the current iteration of a loop to stop, and the next one to begin immediately • The continue statement may only occur inside for , while , and do-while loops for (i = 0; i < TOTAL; i++) { c = getchar(); if (c >= '0' && c <= '9') continue ; ... /* process non-digit characters */

  37. break and continue– Example #include <stdio.h> int main() { int i, j; for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { printf ("%3d ", i * 10 + j); } printf ("\n"); } return 0; }

  38. break and continue– Example • The output of the previous program: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

  39. break and continue– Example • We change the main part of the program: ... for (i = 0; i < 10; i++) { if (i % 3 == 0) continue; for (j = 0; j < 10; j++) { if (j == 8) break; printf ("%3d ", i * 10 + j); } printf ("\n"); } ...

  40. break and continue– Example • The output of the modified program: • The lines beginning with 0, 30, 60 and 90 are skipped (i is a multiple of 3) • All lines are truncated when j reaches 8 10 11 12 13 14 15 16 17 20 21 22 23 24 25 26 27 40 41 42 43 44 45 46 47 50 51 52 53 54 55 56 57 70 71 72 73 74 75 76 77 80 81 82 83 84 85 86 87

  41. Lecture Overview • Boolean expressions • The if statement • The switch statement • Iteration statements –for and while • The break and continue statements • The goto statement

  42. The goto Statement • A goto statement causes an unconditional jump to a labeled statement somewhere in the current function • In order to perform a goto, some special label must be defined • A label is an identifier, with a ':' after it – control will transfer to the statement directly following the label

  43. The goto Statement • The first rule to remember about goto: goto is bad! • Using it may undermine all of the useful structure provided by other control flow mechanisms (such as for and while) • The only possible exception: goto is sometimes used for critical error handling

  44. The goto Statement – Example • Handling errors using goto: ... while (scanf ("%f", &x) == 1) { if (x < 0.0) goto negative_alert; printf ("%f %f\n", sqrt (x), sqrt (2 * x)); } ... negative_alert: printf ("Negative value encountered! \n"); exit (EXIT_FAILURE); ...

  45. The goto Statement From xkcd.com

More Related