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?
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With