Re: Declaring variables in "case" blocks?
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Tue, 31 Jul 2007 00:30:03 -0700
"Robbie Hatley" <see.my.signature@xxxxxxxxxxxxxxxxxxxx> writes:
Greetings, group. I just found a weird problem in a program where
a variable declared in a {block} after a "case" keyword was being
treated as having value 0 even though its actual value should
have been something else. An extremely stripped-down version:
int Function (int something)
{
switch(something)
{
case WHATEVER:
{
int DumVar = 72;
// Some code uses DumVar. It seems to see the value
// of DumVar as being 0 ! What the heck???
break;
}
}
}
I think you've stripped down your code so far that you've eliminated
the error. The above is valid, and code that refers to DumVar will
see its value as 72. You'd have been better off posting a small
compilable program, so you could confirm that the problem is still
there.
But here's an example that illustrates the problem you're having:
#include <stdio.h>
int main(void)
{
int x = 42;
switch(x) {
int DumVar = 72;
case 42:
printf("ok, x = %d, DumVar = %d\n", x, DumVar);
break;
default:
printf("Huh?\n");
break;
}
return 0;
}
The output I get is:
ok, x = 42, DumVar = 1628438944
after a compiler warning:
c.c:6: warning: unreachable code at beginning of switch statement
The problem is that control jumps directly from the 'switch' to the
appropriate 'case' label, in this case to 'case 42:'. After that,
DumVar is visible, but you've skipped over its initialization.
You can safely declare variables within a block following a case
label, but not within a block that's the entire body of the switch
statement.
For more fun with switch statements, see question 20.35 in the
comp.lang.c FAQ, <http://www.c-faq.com/> (Duff's Device).
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.
- Follow-Ups:
- Re: Declaring variables in "case" blocks?
- From: Robbie Hatley
- Re: Declaring variables in "case" blocks?
- References:
- Declaring variables in "case" blocks?
- From: Robbie Hatley
- Declaring variables in "case" blocks?
- Prev by Date: Re: Malcolm's new book
- Next by Date: Re: bytes calculation
- Previous by thread: Declaring variables in "case" blocks?
- Next by thread: Re: Declaring variables in "case" blocks?
- Index(es):
Relevant Pages
|