Switch statement with char[] strange ?
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Mon Jul 3 12:46:33 PDT 2006
DMINATOR wrote:
> Hi
>
> I am only learning D , but I am getting strange result.
> A small part of the code:
>
> switch( "df" ) //Line 64 - error when running
> {
> case "v ":
> break;
> case "vt":
> break;
> case "vn":
> break;
> case "f":
> break;
> }
>
> Gives me this warning message:
> warning - mesh.d(64): switch statement has no default
> warning - mesh.d(64): statement is not reachable
>
> and when I run it, I get:
> Error: Switch Default mesh(64)
>
> --------------------------
> Although when I change it to:
>
> switch( "df" )
> {
> case "v ":
> break;
> case "vt":
> break;
> case "vn":
> break;
> case "f":
> break;
> default:
> }
>
> - it doesn't give any warning or error message at all.
>
> ---------------
>
> I tested it with the latest version 1.062
>
> Is this really how it should be ?
>
>
I assume you mean version 0.162a? :) Actually, yes, this is expected behavior --
although occasionally debated behavior. Let me try to explain.
In the first case you get two warnings. This first warning:
> warning - mesh.d(64): switch statement has no default
This one is simple, and fairly obvious. Warning, you have no default clause for your
switch. If this warning bothers you, add a default clause, even if it does nothing at all
or just throws an exception.
The second warning:
> warning - mesh.d(64): statement is not reachable
This is not neccessarily as obvious, but still true. You are switching on a constant. As
well, all your cases are constants. None of your case constants match your switch
constant -- information available to the compiler, since it does constant folding and
analysis. So, you do have unreachable statements: every single one of your case
statements is unreachable, because it is guaranteed not to match any of them. It reports
line 64 because cases belong to their mother switch, I assume.
You got the following runtime error:
> Error: Switch Default mesh(64)
Remember when I said you could write the default clause to just throw an exception? DMD
automatically adds exactly such a default clause if you don't provide one. :) This is
being thrown from that, since none of your cases will match. (This is why the error
message is simply "Switch Default".)
Now then, in the second version of your code you have added a default clause. This does
eradicate all the above behavior, because now you do have a default (the first warning),
you do have a reachable clause in your switch statement (the default is, afterall, always
reachable by principle), and DMD does not have to insert its automatic default (which was
generating the runtime exception/error).
Make sense? :)
-- Chris Nicholson-Sauls
More information about the Digitalmars-d-learn
mailing list