Using arrays in switch statements?

Oct 12, 2012 at 4:53pm
I was wondering if its possible to put arrays in switch statements, I've tried but I always get an error. Here's what I'm trying to do:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
switch(userNumbers)
            {

            case userNumbers[0] < 50 :
                cout << "Your 1st Number is less than 50" << endl;
                    break;
            case userNumbers[1] < 50 :
                cout << "Your 2nd Number is less than 50" << endl;
                    break;
            case userNumbers[2] < 50 :
                cout << "Your 3rd Number is less than 50" << endl;
                    break;
            case userNumbers[3] < 50 :
                cout << "Your 4th Number is less than 50" << endl;
                    break;
            case userNumbers[4] < 50 :
                cout << "Your 5th Number is less than 50" << endl;
                    break;

With the array been userNumbers[5]
I was going to them into a bunch of if statements, but I feel that's always an easy way out and I wanted give my self a challenge.
Oct 12, 2012 at 5:05pm
The switch statement evaluates the integer expression in parentheses and compares its value to all cases. Each case must be labeled by an integer or character constant or constant expression. Each label must be unique.

So, you can't switch on the userNumbers array. You could use an index into the array and switch on that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

int i = 0;

int max = sizeof( userNumbers ) / sizeof( int );

for( i = 0; i < max; i++ )
    {
    n = userNumbers[ i ];

    if( n < 50 )
        cout << "userNumbers[ " << i << " is less than 50" << endl;

    }    /*    for( i < max )    */



Oct 12, 2012 at 5:16pm
 
case userNumbers[0] < 50 :


VB programmer...
Oct 12, 2012 at 5:29pm
Thanks kooth I'll have a go at it and chipp. If VB means visual basic, I'm not sure what you're on about
Oct 12, 2012 at 5:35pm
it similar to visual basic's select syntax to me, where you can specify the range of your case
Last edited on Oct 12, 2012 at 5:36pm
Oct 12, 2012 at 5:37pm
Oh ok, but this is the first programming language I'm learning
Topic archived. No new replies allowed.