On Sunday, 4 August 2013 at 16:16:25 UTC, Andre Artus wrote:
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).


Like I said, it would be nice if we could extend some D features without change the compiler source, maybe like macros in LISP.

The switch statement should have an event handler like: onBeforeMatch or onAfterMatch to handle this.

But for what I saw on this thread, this is only possible changing the compiler source. :/

Matheus.

Reply via email to