Skip to main content
gamedev.net
🔒 Locked

Case scope?

Started by Sirveaux Jul 19, 2003 at 9:07 PM 2 replies 250+ views
Original Post
Sirveaux
Sirveaux
Does each case in a switch have its own scope? As in, could I declare a variable under a case xx: and have it limited to only that case, or at least inside the switch? Basically, I have a function that is called recursively that won''t need the variable for every instance. I''m sure having it there won''t hurt much, but I''d like to avoid it if it is possible. Why waste the memory? If it doesn''t have its own scope is generally bad practice to declare variables further down into the code? Thanks, Kenneth
quasar3d
quasar3d
as far as I know every scope has it''s own { and }. So the switch statement has it''s own scope, but all case''s use the same scope (That''s why you sometimes get the error "initialization of foo is skipped by the case label", or something like that). if you want a case to have it''s own scope do it like this:

case 0:
{
int foo,bar;
cout << foo << bar << endl:
}
break;

My Site
Sirveaux
Sirveaux
Wow! I wasn''t aware that could be done! Thanks for the help.

Kenneth
drslush
drslush
You can put braces anywhere you want. Braces make up "compound statements" and so can be put anywhere, even without any sort of flow control keywords. This is perfectly legal:


int foobar()
{
int i = 0;
int j = 1;
{
bool i = true;
float j = 0.1f;
}
}



[edited by - drslush on July 19, 2003 10:48:33 PM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.