Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use non-integral types with switch [duplicate]

Cause if I define the operator== then comparison will be possible:

class My
{
    int x;
    // ...
public:
    My(int);

    bool operator==(const My & y);
        // ...
};

//...

My one = 1;
switch (one)
{
    case 1 : // anything

    default : // ...
}

But it's possible only for integer types. Why?

like image 630
vlad4378 Avatar asked Dec 25 '22 17:12

vlad4378


2 Answers

The BCPL and C languages implemented switch (switchon in BCPL) as a higher-level implementation of an assembly branch table.

A branch table is a very efficient implementation of an if/else chain that uses a single integer to index into an array of addresses (or address offsets). Program control jumps to the address at the specified index of the table.

switch requires an integer type (or a type implicitly convertible to an integer) because array-indexing requires an integer type.

C++ inherited the same language properties of switch without making significant changes.

It would be possible to redefine the language to implement switch using operator ==, but that same behavior can already be implemented as an if/else chain.

like image 123
Drew Dormann Avatar answered Dec 28 '22 05:12

Drew Dormann


You can use classes in the switch statement.

According to the C++ Standard (6.4.2 The switch statement):

2 The condition shall be of integral type, enumeration type, or class type. If of class type, the condition is contextually implicitly converted (Clause 4) to an integral or enumeration type.

Here is a demonstrative program

#include <iostream>

class A
{
    int x;

public:
    A( int x ) : x( x ) {}

    operator int() const { return x; }
};

int main()
{
    A a( 2 );

    switch ( a )
    {
        case 1:
            std::cout << "past by" << std::endl;
            break;
        case 2:
            std::cout << "Bingo!" << std::endl;
            break;
    }            
}

The program output is

Bingo!
like image 43
Vlad from Moscow Avatar answered Dec 28 '22 05:12

Vlad from Moscow