request switch statement with common block

Andre Artus andre.artus at gmail.com
Sun Aug 4 09:16:23 PDT 2013


On Sunday, 4 August 2013 at 15:57:32 UTC, Andre Artus wrote:
> On Sunday, 4 August 2013 at 10:14:50 UTC, Kagamin wrote:
>> On Saturday, 3 August 2013 at 18:56:47 UTC, JS wrote:
>>> Um, it can actually save a lot of type and errors.
>>>
>>> having two places to change is very error prone.
>>>
>>> if (cond) { }
>>> switch(cond)
>>
>> What is error-prone is evaluation of a complex condition twice 
>> assuming it will result in the same value. That's also a 
>> common error with C macros. You should save the value in a 
>> variable:
>>
>> auto cond = complexCond;
>> if (cond) { }
>> switch(cond)...
>
> There is also a subtle, but in my opinion important, 
> distinction between the expressions accepted by 'if' and 
> 'switch'.
>
> With 'if' the expression must evaluate to boolean, whereas with 
> 'switch' the expression evaluates to an integral or {w|d}char[] 
> type. With a 'switch' the condition is completed in the 'case'.

Oops. I think I hit spacebar twice and the message was posted 
before I finished it.

Taking an example from the D language reference,

>
> int number;
> string message;
> switch (number)
> {
> 	default: // valid: ends with 'throw'
> 	throw new Exception("unknown number");
> 	case 3:
> 		message ~= "three "; break;
> 	case 4:
> 		message ~= "four "; continue;
> 	case 5:
> 		message ~= "five "; goto case;
> 	case 6:
> 		message ~= "six "; break;
> 	case 1:
> 	case 2:
> 		message = "one or two";
>  }

With the inclusion of 'default' the condition covers the whole 
range of 'int'. The programmer may only want the pre  and post 
code to be executed for every other case (1..6).

switch (number)
{
	default: // valid: ends with 'throw'
		throw new Exception("unknown number");
	case 3:
		message ~= "three ";
		break;
	case 5:
		message ~= "five ";
		goto case;
	case 6:
		message ~= "six ";
		break;
	case 2:
		message = "one or two";
  }

Here the range is interrupted, but covered by 'default'. What 
does the compiler do here?

Sorry I have to go make supper now, but I have a lot more to say 
on this.


More information about the Digitalmars-d mailing list