kremer@cs.odu.edu (Lloyd Kremer) (04/05/89)
I just fell into a little C language trap, and I thought I would warn
others about it. It looks like a very easy mistake to make!
(I've been using C almost exclusively for years.)
Initializing a variable after the opening brace of a switch does not
work. The variable is declared and brought into scope for the
remainder of the switch block, but the initialization does not occur.
Example:
switch(n){
int tmp = 1234;
/*
* This will declare 'tmp' during the switch but
* it will not be set to 1234 !
* It will be garbage!!
*/
case 1:
statement;
break;
case 2:
statement;
break;
default:
break;
}
I tried this program using both MSC 5.1 and also using
UNIX(tm) System V Release 3 (did I really mention those two in
one breath?), and in neither case did initialization take place.
MSC said nothing. Lint caught it as 'statement not reached'.
Is this the pANS conformant behavior? I'm sure it is, but I don't
have a copy to verify it.
Lloyd Kremer
Brooks Financial Systems
{uunet,sun,...}!xanth!brooks!lloyd
friedl@vsi.COM (Stephen J. Friedl) (04/05/89)
In article <8348@xanth.cs.odu.edu>, kremer@cs.odu.edu (Lloyd Kremer) writes: > > I just fell into a little C language trap, and I thought I would warn > others about it. It looks like a very easy mistake to make! > (I've been using C almost exclusively for years.) Don't send these to us, send them to Andrew Koenig :-). Steve P.S. - Pitfalls too... -- Stephen J. Friedl / V-Systems, Inc. / Santa Ana, CA / +1 714 545 6442 3B2-kind-of-guy / friedl@vsi.com / {attmail, uunet, etc}!vsi!friedl "I do everything in software, even DMA" - Gary W. Keefe (garyk@telxon)
henry@utzoo.uucp (Henry Spencer) (04/05/89)
In article <8348@xanth.cs.odu.edu> kremer@cs.odu.edu (Lloyd Kremer) writes: > Initializing a variable after the opening brace of a switch does not > work... > Is this the pANS conformant behavior? I'm sure it is, but I don't > have a copy to verify it. Yes. It's well-hidden, unlike in K&R1 which mentioned it under "switch", but the Oct draft says explicitly that initializations don't get performed when the block is entered by a jump into the middle (which is what a switch does). -- Welcome to Mars! Your | Henry Spencer at U of Toronto Zoology passport and visa, comrade? | uunet!attcan!utzoo!henry henry@zoo.toronto.edu