Declarations in switches, errors

david.f.prosser dfp at cbnewsl.ATT.COM
Fri Sep 29 01:47:24 AEST 1989


In article <1202 at virtech.UUCP> cpcahil at virtech.UUCP (Conor P. Cahill) writes:
>In article <10041 at xanth.cs.odu.edu>, kremer at cs.odu.edu (Lloyd Kremer) writes:
>> No, a switch statement is entered by a jump to a label.  The jump is to
>> any one of several places depending on which "case" is true, but an automatic
>> initialization at the start of a switch statement is never performed.  The
>> variable is brought into scope within the switch block, but the initial
>> contents of the variable are garbage.
>
>If this is the standard, I think it is broken.  If the compiler allows 
>a variable declaration, it should allow an initialization.

The pANS specifies the way the C language works.  Period.  A switch
statement is a multiway jump to a finite set of labels.  If you jump
into a block skipping over certain expressions, these expressions
will not be executed.  Similarly, if you skip over the code for
initialization, it will not be executed.  The allocation of automatic
objects is a slightly different matter, so at least the objects are
guaranteed to exist.

The following example is copied from the pANS, section 3.6.4.2:

	Example
	    In the artificial program fragment

		switch (expr)
		{
			int i = 4;
			f(i);
		case 0:
			i = 17;  /* falls through into default code */
		default:
			printf("%d\n", i);
		}

	the object whose identifier is i exists with automatic
	storage duration (within the block) but is never initialized,
	and thus if the controlling expression has a nonzero value,
	the call to the printf function will access an indeterminate
	value.  Similarly, the call to the function f cannot be
	reached.

There is nothing preventing a translator from warning that the code
will not be reached, but it cannot refuse to compile fragments such
as the above example.

Dave Prosser	...not an official X3J11 answer...



More information about the Comp.std.c mailing list