#include <sstream>
#include <string>
usingnamespace std ;
string talkBack( int x )
{
stringstream buf ( stringstream::out ) ; // excessive but bear with me
switch(x)
{
case 1: // That is, x == 1
buf << "Hello. " ;
// No "break" statement here, so case 1 will also "leak" into case 2.
case 2: // x == 2
buf << "How are you?" ;
break ;
case 3: // x == 3
{ // Because the code for case 3 declares variables, you have to
// put it in braces, sort of like an inline function definition.
// Some people might even prefer to style all case blocks this way.
buf << "I can count to three!"int i = 0 ;
do { buf << " " << ++i ; } while( i < 3 ) ;
} break ;
default: // Magic label for code to be executed when no case value matches.
buf << "Huh?" ;
}
return buf.str() ;
}
int main()
{
for( int i = 0 ; i < 4 ; i++ )
cout << talkBack(i) << endl ;
return 0 ;
}
Of course this is all off the top of my head and I haven't bothered testing it but if you try it I expect that you'd get this output:
1 2 3 4
Huh?
Hello. How are you?
How are you?
I can count to three! 1 2 3
In general, the following two code blocks are exactly equivalent:
1 2 3 4 5 6 7
switch(x)
{
case a: /* stuff A */ ; break ;
case b: /* stuff B */ ; break ;
case c: /* stuff C */ ; break ;
default: /* stuff D */ ;
}
...and...
1 2 3 4
if( x == a ) { /* stuff A */ ; }
elseif( x == b ) { /* stuff B */ ; }
elseif( x == c ) { /* stuff C */ ; }
else { /* stuff D */ ; }
The useful difference is that switch() will let you "leak" from one block of stuff into another by leaving out the break ; statement at the end of a case block, as I illustrated above.