switch problem

Hi, I am new here.
I have a problem with my switch. I was investigating it on the net but I really haven't got the solution yet.

I always get these error- messages:
14 error: 'b' cannot appear in a constant-expression
18 error: 'c' cannot appear in a constant-expression
9 warning: unused variable 'b'
10 warning: unused variable 'c'

The code is very simple:

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
#include <iostream>

using namespace std;

int main()
{
   int a=23;
   int b=22;
   int c=23;

    switch (a)
    {
        case b:
        cout<<" this is b";
        break;

        case c:
        cout<<" this is c";
        break;

        default:
        cout<<"non of them is good";
        break;

     }
    cin.get();

}


Why it does not let me run the program? Since it is a basic scholar example!
Thank you for the answer in advance.

P.S.: I am using Code::Blocks.
The error says it all. The cases must be constant integral expressions (constants known at compile-time).
If you make b and c const, it'll work (at least in this example).

Since it is a basic scholar example!

...which is hopefully supposed to demonstrate that you can't do this with switch.
If not, one has to seriously doubt the competence of whoever contrived this "scholar example".
Last edited on
Thanks a lot. Now It is working changing the those variables to constans.

Why (a) does not have to be converted into a constant? Why only (b) and (c) in this example?

the right code which is running now:
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

#include <iostream>

using namespace std;

int main()
{
   int a=23;
   const int b=27;
   const int c=23;

    switch (a)
    {
        case b:
        cout<<" this is b";
        break;

        case c:
        cout<<" this is c";
        break;

        default:
        cout<<"none of them is good";
        break;

     }
    cin.get();

}


Thank you!!!
Topic archived. No new replies allowed.