D's SwitchStatement accepts statements with ridiculous semantics

sarn sarn at theartofmachinery.com
Sat Sep 30 02:35:09 UTC 2017


On Friday, 29 September 2017 at 09:56:17 UTC, Dukc wrote:
> On Friday, 29 September 2017 at 09:12:54 UTC, Don Clugston 
> wrote:
>> Guess what this prints
>
> My guess is it prints "1".
>
> By "guess" I mean it, I did not test! Anyway reminds me a lot 
> of very badly used gotos.

Yeah, it's a lot like Duff's Device:
https://en.wikipedia.org/wiki/Duff's_device

For anyone who's wondering, it works because switch is just a 
computed goto.  The code's equivalent to this:

import std.stdio;

void main()
{
	int i = 0;

	// switch(i)
	if (i == 7)
	{
		goto case_7;
	}
	else
	{
		goto case_default;
	}

	// for loop initialiser
	i = 8;
	// for loop test
	while (i < 10)
	{
case_7:
		writeln(i);
		return;
case_default:
		// for loop update
		++i;
	}
}


More information about the Digitalmars-d mailing list