No more fall through in case statement?
Bruce Adams
tortoise_74 at yeah.who.co.uk
Thu Jan 3 17:35:48 PST 2008
On Fri, 04 Jan 2008 00:15:25 -0000, S. <S at s.com> wrote:
> Carlos Santander Wrote:
>>
>> How about using existing D syntax?
>>
>> switch (s[i]) {
>> case ' ', '\t', '\f', '\r', '\n', '\v':
>> if (inword) {
>> r ~= capitalize(s[istart .. i]);
>> inword = false;
>> }
>> break;
>>
>> default:
>> if (!inword) {
>> if (r.length)
>> r ~= ' ';
>> istart = i;
>> inword = true;
>> }
>> break;
>> }
>
> This whole conversation about switch was kind of lost on me, but I have
> to contribute this.
>
> I, at various times, have written code that depends on case statements
> falling through, while not being identical!
>
> For example:
>
> switch(foo)
> {
> case 'bob':
> //Do bob stuff
> //Fall through and doo bar stuff too.
> case 'bar':
> //Do bar stuff and exit
> break;
>
> case 'baz':
> //Do some baz stuff
> break;
> }
>
> Whatever is changed shouldn't break this.
This whole conversation boggles me. cases should *never* fall through its
dangerous.
Assuming polymorphism isn't the answer, which can often eliminate the
switch altogether
its much cleaner, safer and better encapsulated in general to use a
function call
to replace fall through. E.g. :
handleBar()
{
//Do bar stuff
}
switch(foo)
{
case 'bob':
// do bob stuff
handleBar();
case 'bar':
handleBar();
case 'baz':
// do baz stuff
}
The switch can always compile to a simple look-up table that way.
More information about the Digitalmars-d
mailing list