Putting arrays in switch functions

I am trying to put an array in a switch function. Why is the code not working? and is it even possible to do this?

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
  #include <iostream>
#include <string>
using namespace std;

void dialog ();

string iceCreamFlavours[4] = {"chocolate", "Vanilla", "Mint", "Chicken"};

int main ()
{
    dialog();
}

void dialog ()
{
    cout << "What type of ice cream would you like?" << endl;
    cin >> iceCreamFlavours[4];
    
switch (iceCreamFlavours)
    {
        case [0]: cout << "Chocolate" << endl;;
        break;

        case [1]: cout << "Vanilla" << endl;
        break;

        case [2]: cout << "Mint" << endl;
        break;

        case [3]: cout << "Chicken" << endl;
        break;

    default: "I'm sorry, we don't have that ice cream type, please enter either chocolate, vanilla, mint or chicken";
    }
}


Thanks.
Last edited on
I think you've misunderstood what a switch/case statement is and how it works.

A switch/case statement basically compares the value of an integer variable to a number of different values, and conditionally executes code based on which of those variables it is equal to. So:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int a;
switch (a)
{
case 1:
  // Do stuff
  break;

case 2:
  // Do other stuff
  break;

default:
  // Do default stuff
  break;
}


is equivalent to:

1
2
3
4
5
6
7
8
9
10
11
12
13
int a;
if (a == 1)
{
  // Do stuff
}
else if (a == 2)
{
  // Do other stuff
}
else
{
  // Do default stuff
}


What you've written doesn't make sense. iceCreamFlavours is an array of strings. It can't be equal to [0], because [0] isn't a value - it's a syntactic construct indicating an array index.

[0] on it's own is meaningless - it needs to be appended to an array name for it to be meaningful. So:

1
2
3
4
5
string iceCreamFlavours[4] = {"chocolate", "Vanilla", "Mint", "Chicken"};

std::cout << iceCreamFlavours[0] << std::endl; // This outputs "chocolate"

std::cout << [0] << std::endl; // This is meaningless, and is illegal C++ 
Topic archived. No new replies allowed.