【问题标题】:Conversion of if condition to ternary operator将 if 条件转换为三元运算符
【发布时间】:2017-08-26 15:22:47
【问题描述】:
status = (Hcill_state == HCILL_STATE_AWAKE)?GPIO_Request(GPIO_5,13):API_FAIL;
上面的代码和下面的代码是等价的吗?
if (Hcill_state == HCILL_STATE_AWAKE)
{
status = GPIO_Request (GPIO_5,13);
}
【问题讨论】:
标签:
c
if-statement
ternary-operator
【解决方案1】:
由于三元运算符定义为:
Condition ? if true : if false
在第二种情况下,您对true 进行了操作,但对false 没有操作。
因此,这些代码不相等,因为在第二个代码中您没有 else 语句。
如果你像这样写第二个,那将是平等的。
if (Hcill_state == HCILL_STATE_AWAKE)
{
status = GPIO_Request (GPIO_5,13);
}
else
{
status = API_FAIL;
}
【解决方案2】:
两段代码并不等价,因为第一段无条件地重新赋值,而第二段只在条件为真时赋值。
第一个代码的等效项将有一个 else 分支将 API_FAIL 分配给 status:
if (Hcill_state == HCILL_STATE_AWAKE)
{
status = GPIO_Request (GPIO_5,13);
}
else
{
status = API_FAIL;
}