allocating new memory in switch statement

I am getting an error with the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void loadLevel(int level)
{
	enum {worldmap,firstlevel};
	switch (level)
	{
	case (worldmap):
		MapLoad("worldmap1.fmp");
		tagItem * handammo = new tagItem(300,300,0);
		player->x = 80;
		player->y = 100;
                break;
	case (firstlevel):
                .....etc...
		break;
	}
}


and it does not like the new tagItem(300,300,0);
i never had a problem using tagitem() until trying to create a new one inside the switch statement. tagItem is just a class that sets x/y position and item type. the error I am getting:

: error C2360: initialization of 'handammo' is skipped by 'case' label

when i comment out the = new statement it is fine. Is there a rule about not allocating new memory inside of a switch statement?
Another note, if I take out the case firstlevel: it works fine too. I would be adding while loops into the switch statements, so it would actually use the new tagItem, but before i dive too far into writing it, i was wondering why it doesn't like this.
it works in an if statement, and i could very easily change it to if statements but i want to understand why this wont work.

thanks a lot
Ed
Last edited on
You can't declare local variables inside a switch block. So you need to encase your code in a block:

1
2
3
4
5
6
7
8
case worldmap:
{
   MapLoad("worldmap1.fmp");
   tagItem * handammo = new tagItem(300,300,0);
   player->x = 80;
   player->y = 100;
   break;
}


Or just write new tagItem(300,300,0); Then you won't need a block since you have no local variable.
thank you very much!
Topic archived. No new replies allowed.