switch()

Daniel Murphy yebbliesnospam at gmail.com
Thu Feb 20 07:29:58 PST 2014


"Steven Schveighoffer"  wrote in message 
news:op.xbk5cxeoeav7ka at stevens-macbook-pro.local...

> Putting default: assert(0); changes the meaning of the code. In other 
> words:
>
> switch(x)
> {
>     case 1: ...
> }
>
> is the same as:
>
> switch(x)
> {
>     case 1: ...
>     default: break;
> }
>
> You are keeping the code the same. I don't think people would think of 
> adding the assert(0), I wouldn't.

Are we talking about writing new code or porting C/C++ code?  If the latter, 
I agree there is a high chance of just copy-pasting in a default: break; 
everywhere the error pops up.

> And as Ary pointed out, it may be that you expect the default to occur, 
> but don't want to do anything.

Sure, and you know this when you write the code and choose the correct one.

> 'if' and 'switch' are commonly used interchangeably. Frequently one uses 
> 'switch' where they would normally use 'if' to avoid evaluating something 
> multiple times.

I'm not sure this is true, at least not in my code. 



More information about the Digitalmars-d mailing list