Search code examples
c++booleancasebreakboolean-expression

Adding boolean expressions switch statements in C++?


I'm practicing switch statements in C++, and I was wondering if I could add a Boolean expression and how, like it's an if/else counterpart. Is it possible to incorporate this?

Here's my skeleton code:

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <Windows.h>
#include <stdlib.h>
#include <time.h>
#include <random>

using namespace std;


int main()
{
    int HouseValue;
    cout << "Enter your total house value estimate:";
    cin >> HouseValue;

    switch (HouseValue)
    {
        case 1:
            (HouseValue < 100000 && HouseValue > 50000);
            cout << "";
            break;
        case 2:
            (HouseValue < 250000 && HouseValue > 100000);
            cout << "";
            break;
        case 3:
            (HouseValue < 500000 && HouseValue > 250000);
            cout << "";
            break;
        case 4:
            (HouseValue < 1000000 && HouseValue > 500000);
            cout << "";
            break;
        case 5:
            (HouseValue < 3000000 && HouseValue > 1000000);
            cout << "";
            break;
    }
    return 0;
}

Solution

  • You can't directly use conditions in a switch, since they require a compile time constant expression. In any case you approach is lacking any branch for exact values (eg. HouseValue == 100000) and it's redundant.

    The simplest solution is to use an if/else chain:

    if (HouseValue < 50000)
      ...
    else if (HouseValue < 100000)
      ...
    else if (HouseValue < 250000)
      ...
    else if (HouseValue < 500000)
      ...