[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Built-in function for `switch'
From: |
John W. Eaton |
Subject: |
Re: Built-in function for `switch' |
Date: |
Fri, 28 Feb 1997 16:26:33 -0600 |
I wrote:
| I believe that the MathWorks web site mentions that MATLAB 5 supports
| a switch statement. Does anyone know what syntax it uses?
On 28-Feb-1997, Guido Dietz <address@hidden> replied:
| This is an Xtract from the manual:
| switch var
| case 1
| disp('1');
| case {2,3,4} % < This is a Cell Array (new feature)
| disp('2 or 3 or 4');
| case 5
| disp('5');
| otherwise
| disp('something else');
| end
| NOTE: Unlike C switch does not 'fall through'!
I just put a patch on ftp.che.wisc.edu in /pub/octave/switch-diffs
that provides a simple-minded implementation of this statement.
The new statement has the following form:
switch EXPRESSION
case LABEL COMMAND_LIST
case LABEL COMMAND_LIST
...
otherwise COMMAND_LIST
endswitch
For example:
switch (x)
case 1
do_one ();
case foo
do_foo ();
otherwise
do_default ();
endswitch
NOTES:
* The identifiers `switch', `case', `otherwise', and `endswitch' are
now keywords.
* The LABEL may be any expression.
* Duplicate LABEL values are not detected. The COMMAND_LIST
corresponding to the first match will be executed.
* You must have at least one `case LABEL COMMAND_LIST' clause.
* The `otherwise COMMAND_LIST' clause is optional.
* As with all other specific `end' keywords, `endswitch' may be
replaced by `end', but you can get better diagnostics if you use
the specific forms.
* Cases are exclusive, so they don't `fall through' as do the cases
in the switch statement of the C language.
* The COMMAND_LIST elements are not optional. Making the list
optional would have meant requiring a separator between the
label and the command list. Otherwise, things like
switch (foo)
case (1) -2
...
would produce surprising results, as would
switch (foo)
case (1)
case (2)
doit ();
...
particularly for C programmers.
* The implementation is simple-minded and currently offers no real
performance improvement over an equivalent if/elseif/else/endif
block, even if all the labels are integer constants. Perhaps a
future variation on this could detect all constant integer labels
and improve performance by using a jump table.
Please send any comments about this to the mailing list
address@hidden
Now for some questions I have about the MATLAB implementation of this
statement:
* Does it require constant labels?
* Do the labels have to be unique?
* Are the command lists optional?
* Is a separator (newline, comma, or semicolon) required between the
case labels and the command lists?
* Are the `case' and `otherwise' clauses optional (i.e., is `switch end'
a valid statement)?
Thanks,
jwe