[Issue 1118] weird switch statement behaviour

Manuel König ManuelK89 at gmx.net
Mon Apr 9 17:16:20 PDT 2007


> ------- Comment #3 from shro8822 at uidaho.edu  2007-04-09 18:41 -------
> Not having a case might not be a problem: tuples can be foreached to generate
> cases and a zero length tuple might be valid. You would however expect their to
> be a default in that case.
> 
> int Foo(A...)(int i)
> {
>  switch(i)
>  {
>   default:
>    // code
>    break;
>   foreach(a;A)
>   {
>    case a:
>     // code
>     // break;
>   }
>  }
> }
> 
> 

Wow, again I'm amazed by D's features! But I could not compile your code 
(yet a real bug :P ). But I could find a workaround:

import std.stdio;

// your version (should work, but it doesn't)
void Foo1(A...)(int i)
{
	switch (i)
	{
		foreach(a; A)
		{
		case a:		// line 9
			writefln(a);
		}
	}
}

// workaround (does exactly the same thing, but with more clumsy code)
void Foo2(A...)(int i)
{
	switch (i)
	{
		foreach(j, a; A)
		{
		case A[j]:
			writefln(a);
		}
	}
}

void main()
{
	//Foo1!(1,2,3,4,5)(1); // line 29
	Foo2!(1,2,3,4,5)(1);
}

The output is
1
2
3
4
5
just as expected. But uncommenting Foo1 gives an error. Error log from 
Code::Blocks:

hello.d:9: Error: case must be a string or an integral constant, not a
hello.d:9: Error: case must be a string or an integral constant, not a
hello.d:9: Error: duplicate case 0 in switch statement
hello.d:9: Error: case must be a string or an integral constant, not a
hello.d:9: Error: duplicate case 0 in switch statement
hello.d:9: Error: case must be a string or an integral constant, not a
hello.d:9: Error: duplicate case 0 in switch statement
hello.d:9: Error: case must be a string or an integral constant, not a
hello.d:9: Error: duplicate case 0 in switch statement
hello.d:29: template instance hello.Foo1!(1,2,3,4,5) error instantiating
:: === Build finished: 10 errors, 0 warnings ===

I think that's worth a bug report.


More information about the Digitalmars-d-bugs mailing list