Declarations in switches, errors

T. William Wells bill at twwells.com
Fri Sep 29 12:28:00 AEST 1989


In article <561 at crdos1.crd.ge.COM> davidsen at crdos1.UUCP (bill davidsen) writes:
: In the process of looking for a totally diferent problem, I generated
: the following program:
:
: main() {
:  int i = 2;
:  switch (i) {
:   int j = 4;
:  case 1: j += 4; break;
:  case 2:
:  case 3:
:  case 'a':
:  case 'b':
:   j--; break;
:  }
: }
:
: Note the initialization in the 4th statement. I was unable to find any
: compiler which generated working code for this initialization (although
: one did complain that the code was not reached). I tried Sun, Ultrix,
: Xenix and gcc compilers.
:
: 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.

dpANS 3.6.1:

"labeled-statement:
	identifier : statement
	case constant-expression : statement
	default : statement"

Case and default are *labels*.

dpANS 3.6.4.2:

"A switch statement causes control to *jump* to, into, or past..."
(Italics mine.)

Also, I believe that K&R explicitly says that this won't work.

---
Bill                    { uunet | novavax | ankh | sunvice } !twwells!bill
bill at twwells.com



More information about the Comp.std.c mailing list