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

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.
You would use default. It is like the else that catches all other cases.
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?
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
}
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
Topic archived. No new replies allowed.