[comp.lang.c] Declarations in switches, errors

davidsen@crdos1.crd.ge.COM (Wm E Davidsen Jr) (09/27/89)

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. Would any of the people still on X3J11 like to comment?

Please let's not discuss the merits (or beauty) of this technique.
Although I was in an attempt to find another compiler error, I can
think of a few places where functional initialization would actually be
useful.

-- 
bill davidsen	(davidsen@crdos1.crd.GE.COM -or- uunet!crdgw1!crdos1!davidsen)
"The world is filled with fools. They blindly follow their so-called
'reason' in the face of the church and common sense. Any fool can see
that the world is flat!" - anon

shankar@hpclscu.HP.COM (Shankar Unni) (09/29/89)

> 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.

Did you consider the remote possibility that the compilers were right and
you were wrong in your proposition?

Read the Dec 88 draft of the proposed ANSI C standard (pages 78,79) for a
good explanation of this. The operative word that it uses is "jump". Not a
normal flow of control, by any stretch of imagination.
-----
Shankar Unni                                   E-Mail: 
Hewlett-Packard California Language Lab.     Internet: shankar@hpda.hp.com
Phone : (408) 447-5797                           UUCP: ...!hplabs!hpda!shankar