Is it possible have Boolean conditions in switch statements?
Asked Answered
C

11

9

I am a programming student in my second OOP class. Is it possible have Boolean conditions in switch statements?

Example:

switch(userInputtedInt)
{
    case >= someNum && <= someOtherNum
    break;
    // Is this possible?
}
Chadd answered 19/1, 2010 at 15:52 Comment(11)
@Neil: Please explain. Should we replace all boolean expressions in a program with a complete class hierarchy?Tutti
Nope. But we shouldn't pretend we are doing OOP - we are doing procedural programming (no cool TLA, unfortunately).Simony
Right. Just because it's not OOP doesn't mean its bad. Take the STL for example. Not even remotely OOP. But would you call it bad?Xymenes
Why can't procedural programming be PART of OOP? I mean, we're not Smalltalk purists here are we? Alternatively, why are switch statements NOT OOP, but if statements are?Drus
@John: Who here is saying things are good or bad? Don't put words in peoples mouths. Neil was simply pointing out that switch statements are not OOP. A hardly debatable point; it just isn't OOP.B
@Brian: And when did Neil say if-statements are?B
@Brian Not an ST purist, but I think that not having a switch is one of the things that ST got right. And any OOP course (and the OP did ask about that) would be flawed IMHO if in its second class it concentrated on switch/case syntax rather than (say) polymorphism.Simony
@Neil I interpreted that as the 2nd COURSE not the 2nd lecture of the 1st course... I agree that even a STRUCTURED programming class shouldn't cover switch in the 2nd lecture. I just think that the value of switch has nothing to do with OOP vs non-OOP... if you don't like them, that's a different thing.@GMan without if statements we can only be in a language like smalltalk where the conditional is a message sent to the boolean object.... (ie we are smalltalk purists B-)Drus
@Brian: What is this without if-statement talk? This isn't a dichotomy where it's either OOP and in C++ or not-OOP and not in C++.B
@GMan: I'm confused. Neil said that Switch isn't OOP. I claim that if and switch are equivalent, in terms of whether or not they are OO, and so if switch isn't OO, then neither is if. If you intend to have an OOP Language without if, then you can only end up with smalltalk, and conversely, if you are allowing if, what are you complaining about with switch?Drus
@Neil We are going to cover that and many other topics, our first class was taught in C#, and as such, C++ is a new language to me. That's why I explicitly asked about switch statements in C++, as my professor did not cover this in his introduction lecture.Chadd
A
17

No this is not possible in C++. Switch statements only support integers and characters (they will be replaced by their ASCII values) for matches. If you need a complex boolean condition then you should use an if / else block

Angevin answered 19/1, 2010 at 15:53 Comment(0)
C
7

No, this is usually the purview of the if statement:

if ((userInputtedInt >= someNum) && (userInputtedInt <= someOtherNum)) { ... }

Of course, you can incorporate that into a switch statement:

switch (x) {
    case 1:
        // handle 1
        break;
    default:
        if ((x >= 2) && (x <= 20)) { ... }
}
Clynes answered 19/1, 2010 at 15:57 Comment(0)
X
7

As others have said you can't implement this directly as you are trying to do because C++ syntax doesn't allow it. But you can do this:

switch( userInputtedInt )
{
  // case 0-3 inclusve
  case 0 :
  case 1 :
  case 2 :
  case 3 :
    // do something for cases 0, 1, 2 & 3
    break;

  case 4 :
  case 5 :
    // do something for cases 4 & 5
    break;
}
Xymenes answered 19/1, 2010 at 15:58 Comment(2)
This is interesting, It's a great use of C++'s support for implicit fall through.Chadd
@Alex: Actually, although this is supported by C++ I have found it is usually less expressive and less useful than you might at first think. Switch statements like this tend to become huge, making them difficult to read, maintain and debug. I will typically use ifs before using a switch like this. Or better yet I'll do something else entirely.Xymenes
S
3

It's not possible directly -- a C or C++ switch statement requires that each case is a constant, not a Boolean expression. If you have evenly distributed ranges, you can often get the same effect using integer division though. e.g. if you have inputs from 1 to 100, and want to work with 90-100 as one group, 80-89 as another group, and so on, you can divide your input by 10, and each result will represent a range.

Sprightly answered 19/1, 2010 at 15:57 Comment(0)
A
1

Or you can perhaps do this

switch((userInputtedInt >= someNum) && (userInputtedInt <= someOtherNum))
{
case true:
     //do something
     break;
case false: 
     //something else
     break;
}

But that's just down-right terrible programming that could be handled with if-else statements.

Aceydeucy answered 30/3, 2011 at 10:47 Comment(0)
H
1

Surprised no one mentioned a very similar way of formatting the switch statment that almost matches what the OP wanted:

    switch (true)
    {
        case userInput >= someNum && userInput <= someOtherNum:
        // ...
    }
Hulky answered 29/8, 2023 at 14:47 Comment(1)
Could you post a working minimal example? I keep getting "error: the value of ‘userInput’ is not usable in a constant expression" if I try this.Harpole
A
0

This isn't possible. The closest you can some, if the values are reasonably close together is

switch(userInputtedInt)
{
    case someNum:
    case someNum+1:
    // ... 
    case someOtherNum:
    break;

}
Aspen answered 19/1, 2010 at 15:56 Comment(0)
P
0

C++ does not support that.

However, if you are not concerned with writing portable, standard code some compilers support this extended syntax:

switch(userInputtedInt)
{
    case someNum...someOtherNum:
    break;
}

Those values must be constant.

Pancho answered 19/1, 2010 at 15:57 Comment(2)
What compilers support that syntax?Rotative
I think I recall Metrowerks supporting it. Perhaps others? It is, of course, merely shorthand for typing several adjacent case labels.Pancho
K
0

If you fancy the preprocessor you could write some kind of macro that auto-expands to the number of case statement required. However that would require a lengthly file with pretty much all case statements (ex: #define CASE0 case 0: #define CASE1 case 1: ...)

You shouldn't go there but it's fun to do...for fun! ;)

Kingcup answered 19/1, 2010 at 16:42 Comment(0)
K
0

The standard does not allow for this:

6.4.2 The switch statement [stmt.switch]

[...] Any statement within the switch statement can be labeled with one or more case labels as follows:

case constant-expression :

where the constant-expression shall be an integral constant expression (5.19).

Klaxon answered 24/5, 2012 at 15:13 Comment(0)
I
0

Some C++ compilers still support range notations today, 8 years after this question was originally asked. It surprised me.

I learned Pascal in 2012, Pascal do have range notations. So it encouraged me to try the similar syntax in C++, then it worked unexpectedly fabulously.

The compiler on my laptop is g++ (GCC) 6.4.0 (from Cygwin project) std=c++17

There is a working example, which I wrote in hurry. repl.it

In addition, the source code is attached as follow:

#include <iostream>
using namespace std;
#define ok(x) cout << "It works in range(" << x << ")" << endl
#define awry cout << "It does\'t work." << endl

int main() {
    /*bool a, b, c, d, e, f, g;
    switch(true) {
        case (a): break;            These does not work any more...
        case (b and c): break;
    }*/
    char ch1 = 'b';
    switch(ch1) {
        case 'a' ... 'f': ok("a..f"); break;
        case 'g' ... 'z': ok("g..z"); break;
        default: awry;
    }
    int int1 = 10;
    switch(int1) {
        case 1 ... 10: ok("1..10"); break;
        case 11 ... 20: ok("11..20"); break;
        default: awry;
    }

    return 0;
}
Ilion answered 27/2, 2018 at 3:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.