switch statements



1
2
3
4
5
6
7
switch (ch)
{
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;

}


If ch is 'a' why does this code display a 3 times?
How does the computer read this? From my understanding since case a is true it would output a once, then it would see that case b is false and therefore it wouldn't output ch.... and the same for case c, but obv I am wrong I just can't figure out why. Thanks.
Banshee1 wrote:
From my understanding since case a is true it would output a once, then it would see that case b is false and therefore it wouldn't output ch
no that's wrong. Once one case evaluates to true, all statements are executed until a break is reached.

This is a common error for beginners.
1
2
3
4
5
6
7
8
9
10
11
12
13
switch (ch)
{
case 'a': 
	cout << ch;
	break;
case 'b': 
	cout << ch;
	break;
case 'c': 
	cout << ch;
	break;

}
Last edited on
Topic archived. No new replies allowed.