Switch constants
Stanislav Blinov
stanislav.blinov at gmail.com
Sat Nov 13 16:38:59 PST 2010
bearophile wrote:
> In a not-ranged cases body, like in the program below (that doesn't compile), the switch variable is a compile-time constant, so why doesn't the compile see x as constant there?
>
>
> template Foo(uint x) {
> static if (x <= 1)
> enum Foo = 1;
> else
> enum Foo = x * Foo!(x - 1);
> }
>
> int bar(uint x) {
> switch (x) {
> case 0: return Foo!x;
> case 1: return Foo!x;
> case 2: return Foo!x;
> case 3: return Foo!x;
> case 4: return Foo!x;
> default: return -1;
> }
> }
>
> void main() {
> assert(bar(4) == 24);
> }
>
>
> That code works if I replace lines like:
> case 2: return Foo!x;
>
> With:
> case 2: return Foo!2;
>
> But when the code isn't DRY bugs may happen...
> (There are ten different better ways to write that program, but this is not the point).
>
> Bye,
> bearophile
I would say that while bar may be CTFE'd, it is nevertheless a function
that can be called at runtime, in which case x may no longer be a
compile-time constant. So there is little compiler can do except for
refusing such code.
More information about the Digitalmars-d-learn
mailing list