Re: The Big Switch
From: Michael Schlenker (schlenk_at_uni-oldenburg.de)
Date: 01/18/05
- Previous message: David Gravereaux: "Re: need help with "after#nnnn" variable corruption"
- In reply to: Ian Bell: "Re: The Big Switch"
- Next in thread: Ian Bell: "Re: The Big Switch"
- Reply: Ian Bell: "Re: The Big Switch"
- Reply: Michael A. Cleverly: "Re: The Big Switch"
- Reply: Donald Arseneau: "Re: The Big Switch"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 18 Jan 2005 19:44:04 +0100
Ian Bell wrote:
> Donal K. Fellows wrote:
>
>
>>That's not going to actually work (unless Ian's incredibly lucky)
>>because the Tcl [switch] command does string comparisons and not
>>numeric comparisons. (I liked the solution based on [lindex], but that
>>really needs some extra code to do the population of the list being
>>indexed into. I'll leave that as an exercise... ;^)
>>
>>Donal.
>
>
> Now I am really confused. Will switch work or not? and what has luck got to
> do with it?
Ok, my switch example may have been a bit to simple. As Donal said,
switch does string comparision, not numeric comparision, so the
following may happen:
0x01 is a hex number for tcl, and this may lead to conversions which
make the switch not working as expected.
Simple example:
set b 0x01
proc sw {val} {
switch --exact -- $val {
0x01 {puts foo}
0x02 {puts bar}
default {puts "unknown: $val"}
}
}
% sw $b
foo
Now force a conversion:
% incr b 0
1
% sw $b
unknown: 1
So the switch works if you can be sure to have the string 0x01 in the
var, but its easy to lose it and have tcl interpret it as a number.
Depending on you specific application, there are two ways to do it:
a) you have integers and just write 0x01 etc. for better readability
b) you have strings and want to match those. (unlikely)
In case a) the fastest way to do things would be to use a tcl list
(which is very similar to a C array in a way) and use the opcode as
index into the list.
Something like this:
set index 0x01
set opcodes { inst foo bar baz }
set cmd [lindex $opcodes $index]
This is fast, but you have to enumerate the opcodes (or write a small
proc to build the list).
You could use a switch like the one i gave if you forced string
conversion with format (but that is quite slow), bevor doing the switch.
like this:
switch --exact -- [format "%#x" $value] {
0x01 { # do something }
0x02 { # do something else}
0x0e { # do a third thing }
}
Michael
- Previous message: David Gravereaux: "Re: need help with "after#nnnn" variable corruption"
- In reply to: Ian Bell: "Re: The Big Switch"
- Next in thread: Ian Bell: "Re: The Big Switch"
- Reply: Ian Bell: "Re: The Big Switch"
- Reply: Michael A. Cleverly: "Re: The Big Switch"
- Reply: Donald Arseneau: "Re: The Big Switch"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|