Is There An Equivalent to the Not Equal Operator for Switch Statements?

Mar 13, 2015 at 7:04am
My question is one I think is possibly a simple one. Is there a way to have a case in a switch statement for the variable NOT being equal to a specific value. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
...
int x;
...

switch(x){

case 1:

...

case != 1:

//I'm fully aware this is improper syntax. My question is what would be the proper syntax, if it's at all possible, to write something like this

... 


Also, let me clarify that I'm fully aware that I could easily just write an if/else statement with one of the conditions being that the variable is not equal to "1", but I would like an equivalent for switch statements, if there is one.
Mar 13, 2015 at 7:09am
You would use default. It is like the else that catches all other cases.
Mar 13, 2015 at 10:01pm
Perhaps this seems like a stupid question, but is there a more specific variant to default ? For example, if I want to reserve default invalid input(such as someone trying to use a char in the case instead of an int) and have a separate case for all other valid inputs, is there a way I could do that?
Mar 13, 2015 at 10:05pm
Perhaps this seems like a stupid question, but is there a more specific variant to default ?


No. default means it covers everything that didn't fall in one of the specified cases. If you want something specific you need to use a case.

For example, if I want to reserve default invalid input(such as someone trying to use a char in the case instead of an int)


switch statements have no concept of input. If you have an int, then it contains an integer. Always. If you put a int in a switch statement, you can only compare it against integers (because that's all it is capable of containing).

Invalid input is another thing entirely and would have to be handled outside the switch. In the case of the user trying to input something that isn't an integer into an int, the stream will go in a bad state:

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

if(cin >> x)
{
    // valid input, run it through the switch
    switch(x)
    {
        //...
    }
}
else
{
    // invalid input
}
Mar 13, 2015 at 10:08pm
closed account (2LzbRXSz)
If you wanted to be specific, you could use an if statement.
For example

1
2
3
4
5
6
7
8
if (x == 1)
    {
        //...
    }
else if (x != 1)
    {
        //...
    }


Edit: Just refreshed the page to find another post in front of mine (that always happens to me for some reason). Sorry for the duplicate reply, didn't mean to spam! Disch has a really thorough reply.
Last edited on Mar 13, 2015 at 10:14pm
Topic archived. No new replies allowed.