Member Avatar for slanker70

Hi,

I've seem to have a problem declaring an object within a switch statement. It keeps saying

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

My code is as below

case 2:
		// 25 % chance of being able to run.
		int roll = Random(1, 4);

		if( roll == 1 )
		{
			cout << "You run away!" << endl;
			return true;//<--Return out of the function.
		}
		else
		{
			cout << "You could not escape!" << endl;
			break;
		}

There are three cases within the switch statement in total. Can somebody please give me some advice on how to solve this problem if it's possible.

Regards,

Perdana Putra

Labels don't introduce a new scope. This error tells you that jumping into the switch can (or does) ignore the definition of the object even though it's still in scope. I'm sure you can imagine what would happen if you try to use an object that doesn't physically exist. A simple way to bypass the problem is to add braces to introduce a new scope:

case 2:
{
	// 25 % chance of being able to run.
	int roll = Random(1, 4);

	if( roll == 1 )
	{
		cout << "You run away!" << endl;
		return true;//<--Return out of the function.
	}
	else
	{
		cout << "You could not escape!" << endl;
		break;
	}
}

This removes the ambiguity by forcing the scope of roll to be exactly within case 2.

commented: *nods* +22

I don't really see the point in initializing this variable in the switch. Could it not be initialized at the start? It's generally considered bad practice to do things like this.

> I don't really see the point in initializing this variable in the switch
How can you say that when you can't see the rest of the code?

If that variable is used only in that case of that switch statement, then Narue's answer is spot on.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.