Compiling the following code and got the error of type illegal
.
int main()
{
// Compilation error - switch expression of type illegal
sw
Why not? You can use switch implementation with equivalent syntax and same semantics.
The C
language does not have objects and strings objects at all, but
strings in C
is null terminated strings referenced by pointer.
The C++
language have possibility to make overload functions for
objects comparision or checking objects equalities.
As C
as C++
is enough flexible to have such switch for strings for C
language and for objects of any type that support comparaison or check
equality for C++
language. And modern C++11
allow to have this switch
implementation enough effective.
Your code will be like this:
std::string name = "Alice";
std::string gender = "boy";
std::string role;
SWITCH(name)
CASE("Alice") FALL
CASE("Carol") gender = "girl"; FALL
CASE("Bob") FALL
CASE("Dave") role = "participant"; BREAK
CASE("Mallory") FALL
CASE("Trudy") role = "attacker"; BREAK
CASE("Peggy") gender = "girl"; FALL
CASE("Victor") role = "verifier"; BREAK
DEFAULT role = "other";
END
// the role will be: "participant"
// the gender will be: "girl"
It is possible to use more complicated types for example std::pairs
or any structs or classes that support equality operations (or comarisions for quick mode).
Sintax differences with language switch is
For C++97
language used linear search.
For C++11
and more modern possible to use quick
mode wuth tree search where return statement in CASE becoming not allowed.
The C
language implementation exists where char*
type and zero-terminated string comparisions is used.
Read more about this switch implementation.