【问题标题】:how do i rewrite this ternary operator in C?我如何用 C 重写这个三元运算符?
【发布时间】:2020-10-31 00:29:27
【问题描述】:

如何在循环而不是三元运算符中编写?

 temp->status = (inStore ? waiting : called);

会是这样吗:

if (inStore){

  return waiting;

}

else (

  return called;

} 

我不确定,因为这样做会出错,我在 void 函数中使用它

【问题讨论】:

  • if (inStore) temp->status = waiting; else temp->status = called; 将等同于第一个代码。我看不出与循环有任何关系。

标签: c conditional-operator


【解决方案1】:

问题在这里:else (。将( 更改为{,你的编译应该是干净的。

ternary operator 只是一个简写语法中的 if-then-else 语句,赋值语句显示为其单个 lvalue。所以:

temp->status = (inStore ? waiting : called);

翻译成:

if(inStore == true)
{
    temp->status = waiting;
}
else
{
    temp->status = called;
}

请注意,您的语法没有任何问题(这里的 "(" 可能除外:else ()。在函数中,如果函数在离开前不需要清理,则最好使用 return 语句。

【讨论】:

    【解决方案2】:

    您必须将waitingcalled 分配给temp->status 变量而不是返回它,同样在else 中您错误地使用了括号。整件事应该是:

    if (inStore)
        temp->status = waiting;
    else
        temp->status = called;
    

    我不确定你为什么在这种情况下要求循环,因为不需要使用循环。

    【讨论】:

      【解决方案3】:
      if(inStore){
         temp->status = waiting;
      } else { // there was a ( instead of a {
         temp->status = called;
      }
      

      【讨论】:

        猜你喜欢
        • 2020-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-12
        • 2021-11-16
        • 2022-01-10
        • 2011-03-16
        • 1970-01-01
        相关资源
        最近更新 更多