About evaluation in loops

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
 
K

Kevin P. Fleming

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...
 
J

John Puopolo

All,

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

John
 
C

cody

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?
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Top