10.2switch语句

根据一个变量的值采取不同的操作是非常常见的。这可以使用if以以下方式语句

if (X == 1)
  do_something ();
elseif (X == 2)
  do_something_else ();
else
  do_something_completely_different ();
endif

然而,这种代码的编写和维护都可能非常麻烦。为了克服这里的问题,Octave支持switch语句使用此语句,上面的示例变成

switch (X)
  case 1
    do_something ();
  case 2
    do_something_else ();
  otherwise
    do_something_completely_different ();
endswitch

这段代码使问题的重复结构体更加明确,使代码更易于阅读,从而便于维护。此外,如果变量X如果要更改其名称,则只有一行需要更改,而当if使用了语句。

的一般形式switch语句为

switch (expression)
  case label
    command_list
  case label
    command_list
  ...

  otherwise
    command_list
endswitch

这里的label可以是任何表达式。但是,重复label未检测到值,只有command_list将执行与第一匹配相对应的操作。对于switch语句要有意义至少一个case label command_list子句必须存在,而otherwise command_list子句是可选的。

如果label是相应的元胞数组吗command_list如果任何的元素匹配expression。例如,以下程序将打印'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

与所有其他特定end关键字,endswitch可能被end,但如果使用特定的形式,则可以获得更好的diag结果。

使用的一个优点switch语句与使用相比if语句是labels可以是字符串。如果if语句被使用了可以写

if (X == "a string") # This is NOT valid

因为之间的字符对字符比较X并且如果字符串相等,则将进行测试而不是评估。此特殊情况从处理switch语句,并且可以编写这样的程序

switch (X)
  case "a string"
    do_something
  ...
endswitch

版权所有 © 2024-2025 Octave中文网

ICP备案/许可证号:黑ICP备2024030411号-2