if / else

if/else 允许比基本的 if 更精细地控制程式码的运行,让多个条件测试可以结合在一起运行;例如,测试一个类比输入值,根据是否小于 500、等于 500 或大于 500,分别执行不同动作。下面是一个 if/else 程式码范例:

if (pinFiveInput < 500)
{
  // 动作 A
}
else
{
  // 动作 B
}

else 可以放在另一个 if 之前,以形成多个互斥且同时运行的条件测试。其中,每个条件测试会依序被执行,直到有一条件测试成立,然后执行关连此条件的程式码区块,略过后续的其它条件测试。如果整个过程没有任何条件测试成立,则会执行最后面的 else 区块(如果此区块存在的话。)

注意一个 else if 区块可以拥有一个终止的 else 区块,但也可以没有。且 else if 的分支数目可以任意多,没有限制。

if (pinFiveInput < 500) 
{   
  // 执行区块 A 
} 
else if (pinFiveInput >= 1000)
{
  // 执行区块 B
}
else
{
  // 执行区块 C
}

另一种表示分支且可同时做多个互斥的条件测试的方法是 switch case 叙述。

See also

switch case


语法参考主页面

本页由热血青年 LBU 译自英文版。

The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.