request switch statement with common block

Andre Artus andre.artus at gmail.com
Sun Aug 4 08:57:30 PDT 2013


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'.

Taking an example from

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";
  }


More information about the Digitalmars-d mailing list