ideas needed - how to do PHP-like switch with strings?

Discussion in 'C++' started by A, May 25, 2010.

  1. A

    A Guest

    so in php you can write nicely:

    switch (case)
    case "a": break;
    case "whatever": break;
    case 0: break;
    case 40: break;

    in C++ all you can use is ordinal types like int and so on. so any ideas how
    would one use strings as well? I use CBuilder 2009 so ideas may be also
    biased toward that one if it has some specific class to do this.
    A, May 25, 2010
    1. Advertisements

  2. Define enumerators with those values, then a function that converts a
    string into those enumerators, then do

    switch (enumerator_from_str(case))
    case a_enumerator: ...
    case whatever_enumerator: ...
    case 0: ...
    case 40: ...
    default: ...

    There is no problem really since you're not trying to use run-time
    values in the 'case', only in the 'switch'. Otherwise, just write a
    bunch of 'if-else-if' statements.

    Victor Bazarov, May 25, 2010
    1. Advertisements

  3. No good advice. In fact you end up with the same problem in the
    conversion function.

    If you really want to speed up things you need an ordered lookup table
    or something like that.

    Marcel Müller, May 25, 2010
  4. How is it "the same"? If the OP wanted to use a switch statement, there
    is no escape from using compile-time constants,
    <shrug> I don't understand the basis of your objections. What prevents
    one from doing that in the conversion function? There are no "ordered
    lookup tables" for use in a 'switch' statement, AFAIK, you're stuck with
    integrals, moreover with constants. Or do you know something I don't?
    Care to demonstrate?

    Victor Bazarov, May 25, 2010
  5. A

    Kaar Guest

    I think the reply is trying to indicate that you will end up doing an
    if-else-if in the function. This is bad, because on new additions, you
    will have to change the if-else-if and then come back and change the
    case. Eventually, this will become tedious and/or error prone and/or
    long and/or ugly.
    My advice would be to program C++ and not try and program PHP in C++. C
    ++ has its reasons for not allowing switches on strings or characters.
    So as in all other cases, think what might those reasons be instead of
    trying to circumvent them. The use of enumerators is a better practice
    (again when writing C++, other languages may actually welcome other
    kinds of switches) and more conformant with the rest of the language
    features, so instead of adapting the language to your design, adapt
    your design to the language to be able to get the full power out of

    Kaar, May 26, 2010
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.