Is there no switch function in Python

Isaac To iketo2 at netscape.net
Fri Sep 10 10:25:34 EDT 2004


>>>>> "Roy" == Roy Smith <roy at panix.com> writes:

    Roy> The real reason, IMHO, switch existed in C was because it
    Roy> would let the compiler build very efficient jump tables for
    Roy> switches with many cases.  Imagine switching on the ascii
    Roy> value of a character and having a 128 different cases.  The
    Roy> compiler could build a 128 entry jump table and the switch
    Roy> statement would compile down to a single machine instruction.

C switch is much more flexible than one would expect.  It is not just
a cheap replacement of a sequence of if-then-else.  E.g., in an
exercise of "The C++ Programming Language" of Bjarne Stroustrup, you
can see the following example code:

  void send(int *to, int *from, int count) {
    int n = (count + 7) / 8;
    switch (count % 8) {
    case 0: do { *to++ = *from++;
    case 7:      *to++ = *from++;
    case 6:      *to++ = *from++;
    case 5:      *to++ = *from++;
    case 4:      *to++ = *from++;
    case 3:      *to++ = *from++;
    case 2:      *to++ = *from++;
    case 1:      *to++ = *from++;
      } while (--n > 0);
    }
  }

Note that this reduces the number of branch statements to execute
8-folds for any compiler but the smartest (as compared to the simplest
code "do { *to++ = *from++ } while (--count > 0);").

I'd instead guess that C has switch because at the times before C,
people code in assembly, and those tricks are popular.  The design of
most programming language represents the norm of coding at that time.

Regards,
Isaac.



More information about the Python-list mailing list