octave: The switch Statement
10.2 The switch Statement
=========================
It is very common to take different actions depending on the value of
one variable. This is possible using the ‘if’ statement in the
following way
if (X == 1)
do_something ();
elseif (X == 2)
do_something_else ();
else
do_something_completely_different ();
endif
This kind of code can however be very cumbersome to both write and
maintain. To overcome this problem Octave supports the ‘switch’
statement. Using this statement, the above example becomes
switch (X)
case 1
do_something ();
case 2
do_something_else ();
otherwise
do_something_completely_different ();
endswitch
This code makes the repetitive structure of the problem more explicit,
making the code easier to read, and hence maintain. Also, if the
variable ‘X’ should change its name, only one line would need changing
compared to one line per case when ‘if’ statements are used.
The general form of the ‘switch’ statement is
switch (EXPRESSION)
case LABEL
COMMAND_LIST
case LABEL
COMMAND_LIST
...
otherwise
COMMAND_LIST
endswitch
where LABEL can be any expression. However, duplicate LABEL values are
not detected, and only the COMMAND_LIST corresponding to the first match
will be executed. For the ‘switch’ statement to be meaningful at least
one ‘case LABEL COMMAND_LIST’ clause must be present, while the
‘otherwise COMMAND_LIST’ clause is optional.
If LABEL is a cell array the corresponding COMMAND_LIST is executed
if _any_ of the elements of the cell array match EXPRESSION. As an
example, the following program will print ‘Variable is either 6 or 7’.
A = 7;
switch (A)
case { 6, 7 }
printf ("variable is either 6 or 7\n");
otherwise
printf ("variable is neither 6 nor 7\n");
endswitch
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.
One advantage of using the ‘switch’ statement compared to using ‘if’
statements is that the LABELs can be strings. If an ‘if’ statement is
used it is _not_ possible to write
if (X == "a string") # This is NOT valid
since a character-to-character comparison between ‘X’ and the string
will be made instead of evaluating if the strings are equal. This
special-case is handled by the ‘switch’ statement, and it is possible to
write programs that look like this
switch (X)
case "a string"
do_something
...
endswitch
Menu