passing array element to switch

Hello,

I was wondering if anyone knows if you can pass an array element to a switch statement. For example I have an array of int's from 1-12. I am trying to pass the int's to a switch statement and return a string representing the correct month. Zero would return January, one February, etc..

This is what I have so far:
1
2
3
4
5
6
7
8
9
10
11
12
string getMonth(int month[]) {
		
	switch (month) {
		case 0:
			return "January";
		case 1:
		    return "February";
	    default:
	        return "nope";
	}

}   


Thanks,
Brad
You need to index the array element with the [] operator.

But, don't use a switch. Use a lookup table instead:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const char* month_names[] =
  {
  "January",    "February",  "March",     "April",
  "May",        "June",      "July",      "August",
  "September",  "October",   "November",  "December"
  };

int main()
  {
  int month;

  cout << "Enter the number of a month (1-12) to see its name> ";
  while (true)
    {
    cin >> month;
    if ((1 > month) or (month > 12))
      cout << "What? Try again> ";
    else break;
    }
  month--;  // indices are 0..11

  cout << "The name of that month is " << month_names[ month ] << ".\n";
  return 0;
  }


Hope this helps.
Last edited on
yes thanks.
take care.
Wow, fast!

It occurs to me that I didn't actually answer your question.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

void my_func1( int x )
  {
  cout << x << endl;
  }

void my_func2( int xs[], int index )
  {
  cout << xs[ index ] << endl;
  }

int main()
  {
  int ten[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  my_func1( ten[ 6 ] );
  my_func2( ten, 6 );
  return 0;
  }

Hope this helps too. :-)
Topic archived. No new replies allowed.