switch()
Steven Schveighoffer
schveiguy at yahoo.com
Thu Feb 20 07:01:35 PST 2014
On Wed, 19 Feb 2014 04:42:19 -0500, Daniel Murphy
<yebbliesnospam at gmail.com> wrote:
>
> "Steven Schveighoffer" wrote in message
> news:op.xbhnw5rbeav7ka at stevens-macbook-pro.local...
>
>> It may not be mindless. Most people who want to handle the default case
>> do it. It's usually not so much "I didn't think of handling other
>> values," it's more "I never expect other values to come in, go away
>> annoying compiler error."
>
> So why not put an assert(0) in instead of a break? Tell the compiler
> that you're assuming there are no other possible values. This is
> obviously the right thing to do here, and even if you ignore it the
> compiler _is_ trying to help you.
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.
And as Ary pointed out, it may be that you expect the default to occur,
but don't want to do anything.
>> I think it's the same as saying you have to always have an else clause
>> after an if statement, even if it's "else {}"
>
> If 'if' was primarily used for the same thing that switch is, this would
> be perfectly reasonable.
'if' and 'switch' are commonly used interchangeably. Frequently one uses
'switch' where they would normally use 'if' to avoid evaluating something
multiple times.
-Steve
More information about the Digitalmars-d
mailing list