Need help about switch function.

I wrote a code and have no idea where is the mistake(s)
I want to learn about the switch function, I want to keep it

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
  /// the selective structure: switch
#include <iostream>
using namespace std;

int main()
{
	int x;
	cout<<"Please enter an integer number: ";
	cin>>x;
	switch (x){
		case 1:
			if (x==0){	
				cout<<"x is equal 0";
				break;
		}
		case 2:
			if (x>0){
				cout<<"x is more than 0";
				break;
		}
		case 3:
			if (x<0){
				cout<<"x is less than 0";
				break;
		}
		default:
				cout<<"x is unknown";
	}
  return 0;
}
Last edited on
Keep the if statements, remove the switch-case stuff completely.
closed account (18hRX9L8)
In this case, you can only keep one switch-case (the case: 0), because cases do not use operators. So if you wanted to have all possibilities, you would need to have 65000+ * 2 cases... Therefore, in this case, you would have to let go of the cases...

Ex:
1
2
3
4
5
6
7
8
9
10
11
switch(x) {
         ...
         case -65000: cout << "x is less than 0"; break;
         case -64999: cout << "x is less than 0"; break;
         ...
         case 0: cout << "x is equal to 0"; break;
         ...
         case 64999: cout << "x is greater than 0"; break;
         case 65000: cout << "x is greater than 0"; break;
         ...
}


Also, you are having cases and then ifs, so none of the cases will ever run because case 1: means that x is 1 but then you check for 0, so 1 != 0, so it will not print out anything. For the case 2:, you are checking if x > 0, and in this case, 2 > 0, so it will print out x is more than 0 only when x is 2. For the last one, it will be like the first one. case 3: will only be run when x is 3, but you are checking for x < 0. 3 !< 0, so nothing will ever get printed out. The default case will get used the most because you are only checking for 3 / (65000+ * 2) cases.

So in this case, you will have to use something like this:
1
2
3
4
5
6
7
if(x == 0) {
        cout << "x is equal to 0";
} else if(x < 0) {
        cout << "x is less than 0";
} else {
        cout << "x is greater than 0";
}


If you really want to use cases, do something like this (not recommended):
1
2
3
4
5
6
7
8
9
10
switch(x) {
        case 0: cout << "x is equal to 0"; break;
        default: {
                if(x > 0) {
                        cout << "x is greater than 0";
                } else {
                        cout << "x is less than 0";
                }
        }
}
Last edited on
I don't know where you got the magic number 65000 from - the range of an int expecially is different from compiler to compiler, platform to platform, etc.
Last edited on
Topic archived. No new replies allowed.