• 0

[C++] Confused about why this is the output...


Question

int main(void)
{
	int a = 4;
	int b = 45;

	switch(a)
	{
  default:
  b = 5;
  cout << “Mouse\n”;

  case 1:
  b = 25;
  cout << “Dog\n”;

  case 2:
  b = 12;
  cout << “Cat\n”;

  case 3:
  b = 24;
  cout << “Lemur\n”;
	} 	 

	cout << b << endl;

	b = 12;  
	a = 6;
	double c = 4.5;

c = (b > a ? 1.2 : a+b);

cout << c << endl;

if(b)
	cout << “Yes\n”;
else
	cout << “No\n”;

return 0;
}

The output (of the first part, which is what I'm concerned about) is:

Mouse

Dog

Cat

Lemur

Now... we initialize a to be 4... so since there is no "case 4:" statement, I'd assume the program only jumps to the default statement and prints out "Mouse". Why does it print out the other statements?

Link to comment
Share on other sites

1 answer to this question

Recommended Posts

  • 0

You need the break keyword after the code you want run for each case. Without the break statement, code execution will "fall through" to the next case, executing those statements, and then the next case, and so on. Your code should look like this:

switch(a)
{
 case 1:
 b = 25;
 cout << ?Dog\n?;
 break;

 case 2:
 b = 12;
 cout << ?Cat\n?;
 break;

 case 3:
 b = 24;
 cout << ?Lemur\n?;
 break;

 default:
 b = 5;
 cout << ?Mouse\n?;
 break;
}

Notice I put the default case last. I don't know if it really matters, but I've always seen it done that way.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.