Control Flow in C
Note: All the programs mentioned in this lecture are in:/home/cs352/SUMMER02/lecture5progs/
- CONTROL FLOW - if (expression) statement -->if expression is nonzero statement is executed. - if (expression) statement1 else statement2 -->if expression is true statement1 is executed and statement2 is skipped, otherwise statement2 is executed - dangling else problem: if (i==5) if (j==5) if (j==5) if (j==10) if (j==10) if (j==10) printf("%c\n", i); ==> printf(... OR printf(... else else else printf("%c\n", j); printf(... printf(... - switch statement: (see whileloop.c) -->switch(integral_expr){ case 'const_integral1': statement_1 break; case 'const_integral2': statement_2 break; ... default: statement_n } NOTE:What happens if we don't have the break statements?? - while and for loops(equivalent): -->for (expr1; expr2; expr3) expr1; statement == while (expr2){ nextstatement statement expr3; } nextstatement -->see whileloop.c - can use the comma operator to create a new expression expr1, expr2 is a legal expression(its value and type is the value and type of expr2. Ex: sum=0; for (i=0; i<=5; i++) == for (sum=0, i=0; i<=5; sum+=i, i++) sum += i; - break and continue statements - break causes to exit from the innermost while loop, for loop or switch - continue(only in while and for loops) causes the current iteration stop and the next iteration begin immediately. (see continue.c) - the conditional operator: expr1 ? expr2 : expr3 expr1 is evaluated firts, if nonzero then expr2 is evaluated, otherwise expr3. NOTE: the value of the whole expression is either the value of expr2 or expr3 as stated. But the type of the expression depends on both(say if epxr2 and expr3 are of diff. types then usual conversion rules apply.)