Declarations in switches, errors

Larry Jones scjones at sdrc.UUCP
Fri Sep 29 07:15:26 AEST 1989


In article <561 at crdos1.crd.ge.COM>, davidsen at crdos1.crd.ge.COM (Wm E Davidsen Jr) writes [edited]:
>  switch (i) {
>   int j = 4;   /* this initialization doesn't happen! */
>  case 1: j += 4; break;
>  case 2:
>  }
> 
> This is an error in the compilers! As ugly as this is, the ANSI standard
> (3.1.2.4) says "If an initialization is specified for the value stored
> in the object, it is performed on each normal entry, but not if the
> block is entered by a jump to a label."
> 
> I submit that executing a switch statement constitutes "normal entry"
> and that the initialization should be performed before evaluating the
> switch variable. Would any of the people still on X3J11 like to comment?

Sure!  If you look at Section 3.6.4.2 (The switch statement), you
will find that:

	A switch statement causes control to jump to, into, or
	past the statement that is the switch body, depending on
	the value of a controlling expression, and on the
	presence of a default label and the values of any case
	labels on or in the switch body.

Thus, a case statement is just a specialized form of goto and case
labels are just that -- labels.  You are not entering the body
normally, you are jumping into it.

Looking further in the same section shows an example which looks
remarkably like yours with the explaination that the variable
exists within the switch body, but is never initialized.
----
Larry Jones                         UUCP: uunet!sdrc!scjones
SDRC                                      scjones at SDRC.UU.NET
2000 Eastman Dr.                    BIX:  ltl
Milford, OH  45150-2789             AT&T: (513) 576-2070
"I have plenty of good sense.  I just choose to ignore it."
-Calvin



More information about the Comp.std.c mailing list