hvn-network

My Blog List

Monday, September 19, 2016

[C programming] control flow

We cover below parts.
- Statements and blocks
- If-else
- Else-if
- Switch
- Loops -While and For
- Loops - Do While
- Break and Continue
- Goto and labels

1. Statements and blocks
An expression such as x = 0 or i++ or printf(...) becomes a statement when it is followed by a semicolon, as in

x = 0;

Braces { and } are used to group declarations and statements together into a compound statement, or block, so that they are syntactically equivalent to a single statement.

2. If-else

if (expression)
      statement1
else
      statement2

3. Else-If

if (expression)
       statement
else if (expression)
       statement
else if (expression)
       statement
else if (expression)
       statement
else
       statement

4. Switch

switch (expression) {
case const-expr: statements
case const-expr: statements
default: statements

}
Below example to count digits, white space, others.


main() /* count digits, white space, others */
{
 int c, i, nwhite, nother, ndigit[10];
 
 nwhite = nother = 0;
 
 for (i = 0; i < 10; i++)
 ndigit[i] = 0;
 
 while ((c = getchar()) != EOF) {
  switch (c) {
  case '0': case '1': case '2': case '3': case '4':
  case '5': case '6': case '7': case '8': case '9':
  ndigit[c-'0']++;
  break;
  case ' ':
  case '\n':
  case '\t':
  nwhite++;
  break;
  default:
  nother++;
  break;
  }
 }
 
 printf("digits =");
 
 for (i = 0; i < 10; i++)
 printf(" %d", ndigit[i]);

 printf(", white space = %d, other = %d\n", nwhite, nother);
 
 return 0;
}
The break statement causes an immediate exit from the switch.

5. Loops - While and For
We have already encountered the while and for loops. In

while (expression)
       statement

the expression is evaluated. If it is non-zero, statement is executed and expression is re-evaluated. This cycle continues until expression becomes zero, at which point execution resumes after statement.

The for statement

for (expr1; expr2; expr3)
       statement

is equivalent to
expr1;
while (expr2) {
        statement
       expr3;
}

for (;;) {
...
}
is an ``infinite'' loop,

6. Loops - Do-While
do
       statement
while (expression);

7. Break and Continue

The break statement provides an early exit from for, while, and do, just as from switch.

The continue statement is related to break, but less often used; it causes the next iteration of the enclosing for, while, or do loop to begin. In the while and do, this means that the test part is executed immediately; in the for, control passes to the increment step. The continue statement applies only to loops, not to switch.

8. Goto and labels
C provides the infinitely-abusable goto statement, and labels to branch to.

for ( ... )
    for ( ... ) {
      ...
      if (disaster)
           goto error;
   }

...
error:
/* clean up the mess */


No comments:

Post a Comment