4

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
vlad4378
  • 803
  • 1
  • 9
  • 21

3 Answers3

6

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.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
3

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!
nobody
  • 19,814
  • 17
  • 56
  • 77
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

You can add an implicit conversion operator to your class to make this possible:

operator int() const { return x; }
Emil Laine
  • 41,598
  • 9
  • 101
  • 157