--- In [email protected], ayyaz <ayya...@...> wrote:
> Steve Searle wrote:
> > ayyaz scrawled:
> > >      switch (choice = getchar()) {
> > >      case 'r':
> > >
> > >      case 'R':
> > >          printf("RED");
> > >          break;
> > >
> > >      case 'w':
> > >
> > >      case 'W':
> > >          printf("WHITE");
> > >          break;
> > >      }
> > >
> > > Should it not only output 'RED' or 'WHITE' when you
> > > enter 'R' or 'W'?
> > 
> > You don't have a break following the case 'r': and
> > case 'w': statements. So control passes to the next
> > statement - the corrosponding upper case ones.
> 
> 1) Why does control pass it to the next statement when
> the next statement is 'R' which is not equivalent to 'r'?

Because 'case' labels are just labels. Switches are like
big 'goto's. If something matches the case, then 'goto'
that statement.

C allows you to label any statement. It doesn't limit how
many labels you have for a given statement, though case
labels must appear inside of a switch statement.

Consider the following...

  int foo(int n, const int a[], int x)
  {
    int i, j, s;
  
    for (i = 0; i < n; i++)
    {
      for (s = j = 0; j <= i; j++)
      {
        if (    a[j] <= 0
             || a[j] > (INT_MAX - s) / a[j] )
        {
          i = -1;
          goto err;
        }
  
        s += a[j] * a[j];
        if (s >= x)
          goto fin;
      }
    }
  
  err:
  fin:
    return i;
  }

Here, I've labelled the final return statement twice. There
are two cases where I want to jump to it: on error, and on
success.

Case labels are no different. You can (almost) have as many
as you want. They don't mark separate blocks of statements,
they just mark individual statements that code can jump to.

Note that labels _must_ mark statements. You can't have a
label on its own...

  void foo(void)
  {
    ... processing that does goto fin; ...
    fin:
  }

You need...

  void foo(void)
  {
    ... processing that does goto fin; ...
    fin:
      ;   /* null statment lebelled fin */
  }

Once you understand that case labels are just labels, and
you can have many marking the same statement, then the
jump to and flow through effects of switch statements
become clearer...

  case 'r': case 'R': /* come here if r or R */
                      printf("RED");
                      break;
  case 'w': case 'W': /* come here if w or W */
                      printf("WHITE");
                      break;

-- 
Peter

Reply via email to