How to complex switch?
KennyTM~
kennytm at gmail.com
Thu May 12 07:20:42 PDT 2011
On May 12, 11 20:04, matthew ong wrote:
> Hi KennyTM~,
>
> Some of the valid reason:
> 1) Less key stroke
Invalid,
switch (x = f()) {
case x < 0: return -x
default: return x
}
50 significant characters
auto x = f();
if (x < 0) return -x;
else return x;
41 significant characters
> 2) Easier code generator to implement
Invalid. Both share the same structure.
switch (x = <variable>) {
case <condition>: <statements> break;
case <condition>: <statements> break;
default: <statements> break;
}
auto x = <variable>;
if (<condition>) { <statements>; }
else if (<condition>) { <statements>; }
else { <statements>; }
> 3) Better to read.
I don't think so.
> 4) less worries about braket '{'.
More worries about missing 'break;' (bad C heritage)
> 5) ....
....
>
> In Java, C++ we avoided using switch because it ONLY support const& literal type.
>
D also only supports literals types. A 'switch' statement is often
implemented as a look-up table when compiled, so keeping the cases a
compile-time constant helps to generate more efficient code. If you can
supply an arbitrary condition or a regex, this advantage is lost and
it's no better than a if/else-if/else chain.
> Most script base language supports things like this. I believe bash shell script
> does. Since D aimed to be a next generation language,
> I suppose that should be in with fall through also.
>
No one forced a "next generation language" have to have a 'switch' with
conditional or regex cases. Look, Python 3 doesn't even have a 'switch'.
More information about the Digitalmars-d
mailing list