Click to See Complete Forum and Search --> : Switch statement with < or >
Atomon
Nov 18th, 2003, 07:46 AM
i want to make a switch statementt that uses < or >. it is for a simple program that takes a grade out of 100 and assigns a letter grade. how can i do this? do i need to stick to a whole bunch of if statements, or can this be done?
Mongo
Nov 19th, 2003, 09:50 PM
While you could try using fall-through or goto's, it'll still be a lengthy switch.
Why not KISS with a pure (?) conditional operator?
int score = 80;
string Ltr_Grade = score > 92 ? "A":
score > 80 ? "B":
score > 70 ? "C":
score > 62 ? "D": "F";
Console.WriteLine( "Your letter grade is: " + Ltr_Grade );HTH.
Atomon
Nov 20th, 2003, 08:27 AM
Originally posted by Mongo
While you could try using fall-through or goto's, it'll still be a lengthy switch.
Why not KISS with a pure (?) conditional operator?
int score = 80;
string Ltr_Grade = score > 92 ? "A":
score > 80 ? "B":
score > 70 ? "C":
score > 62 ? "D": "F";
Console.WriteLine( "Your letter grade is: " + Ltr_Grade );HTH.
hmmm... the only c# i know is from a high school course i'm taking. i have never seen this operator before. what does it do/how does it work?
CornedBee
Nov 20th, 2003, 09:29 AM
cond ? expr1 : expr2
If cond is true, the result is expr1. Else it's expr2.
However nesting them like Mongo did makes for terribly unreadable code.
You can only have constants in switch cases. You should use if...else if...else chains for places where you need expressions.
wossname
Nov 25th, 2003, 10:37 AM
I like Mongo's code even though it's tough on the brain. I've not seen that particular way of using of ?: before.
It's a bugger to read though like Cornedbee said.
Would that code be faster / slower than the equivalent if() statements?
wossname
Nov 25th, 2003, 10:42 AM
it looks a bit more obvious like this...
int score = 80;
string Ltr_Grade =
score > 92 ? "A":
score > 80 ? "B":
score > 70 ? "C":
score > 62 ? "D":
/*default*/ "F";
Console.WriteLine( "Your letter grade is: " + Ltr_Grade );
...but not much
wossname
Nov 25th, 2003, 10:44 AM
Or maybe...
int score = 80;
string Ltr_Grade = (score > 92 ? "A": (score > 80 ? "B": (score > 70 ? "C": (score > 62 ? "D": /*default*/ "F"))));
Console.WriteLine( "Your letter grade is: " + Ltr_Grade );
CornedBee
Nov 25th, 2003, 11:20 AM
Whether if or ? is faster depends solely on the compiler.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.