About evaluation in loops

  • Thread starter Thread starter Dennis Myren
  • Start date Start date
D

Dennis Myren

Hi.
This is not a critical question.
Consider this snippet:

switch ((myenum) hashtable [key])
{
case myenum.first :
...
}

I just want to know whether the expression
(myenum) hashtable [key]
needs to be evaluated for each case declared in the switch
statement.
The alternative would be as i have done yet to make sure:
myenum var = (myenum) hashtable [key];
switch(var)
....

Thank you
 
Dennis said:
switch ((myenum) hashtable [key])
{
case myenum.first :
..
}

I just want to know whether the expression
(myenum) hashtable [key]
needs to be evaluated for each case declared in the switch
statement.

I would be shocked to find out that the compiler wasn't smart enough to
optimize this on its own... most compilers turn switch statements into
jump tables, sometimes with binary trees used to short-circuit large
parts of the table. This really wouldn't be possible unless the
expression was only evaluated one time and the result stored in a
temporary location...
 
All,

Simply take a look at the IL generated and you will know *exactly*
what happens. The beauty of ILDASM...

John
 
switch ((myenum) hashtable [key])
{
case myenum.first :
..
}

I just want to know whether the expression
(myenum) hashtable [key]
needs to be evaluated for each case declared in the switch
statement.
The alternative would be as i have done yet to make sure:
myenum var = (myenum) hashtable [key];
switch(var)


It is guaranteed by the language that the expression in the switch is
evaluated exactly one time.

But what does this have to do with loops as you stated in the headline?
 
Back
Top