Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cs.utexas.edu!uwm.edu!uakari.primate.wisc.edu!ginosko!brutus.cs.uiuc.edu!psuvax1!rutgers!dptg!att!cbnewsl!dfp From: dfp@cbnewsl.ATT.COM (david.f.prosser) Newsgroups: comp.std.c Subject: Re: Declarations in switches, errors Message-ID: <2038@cbnewsl.ATT.COM> Date: 28 Sep 89 15:47:24 GMT References: <1202@virtech.UUCP> Reply-To: dfp@cbnewsl.ATT.COM (david.f.prosser) Organization: AT&T Bell Laboratories Lines: 46 In article <1202@virtech.UUCP> cpcahil@virtech.UUCP (Conor P. Cahill) writes: >In article <10041@xanth.cs.odu.edu>, kremer@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...