function that chooses action based on integer value

What's that one function that, based on the integer value of the input, will choose an action? The one that uses cases and such.
Maybe assert??
I believe you're looking for switch().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <sstream>
#include <string>
using namespace 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 */ ; }
else if( x == b ) { /* stuff B */ ; }
else if( 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.

FYI, the switch() syntax is also used in Java.

I hope this helps.
Topic archived. No new replies allowed.