我如何在 C 中重写这个三元运算符?
how do i rewrite this ternary operator in C?
如何在循环而不是三元运算符中写入?
temp->status = (inStore ? waiting : called);
会不会像:
if (inStore){
return waiting;
}
else (
return called;
}
我不确定,因为我在执行此操作时遇到错误,我在 void 函数中使用它
您必须将 waiting
或 called
分配给 temp->status
变量而不是返回它,同样在 else
中您错误地使用了括号。整个事情应该是:
if (inStore)
temp->status = waiting;
else
temp->status = called;
我不确定你为什么要在那种情况下使用循环,因为没有必要使用循环。
问题在这里:else (
。将 (
更改为 {
,您的编译应该是干净的。
ternary operator 只是快捷语法中的 if-then-else
语句,赋值语句显示为单个 lvalue
。所以:
temp->status = (inStore ? waiting : called);
翻译成:
if(inStore == true)
{
temp->status = waiting;
}
else
{
temp->status = called;
}
请注意,您的语法没有任何问题(除了此处的 "("
:else (
)。在函数中,如果函数在离开前不需要清理,则最好使用 return
语句。
if(inStore){
temp->status = waiting;
} else { // there was a ( instead of a {
temp->status = called;
}
如何在循环而不是三元运算符中写入?
temp->status = (inStore ? waiting : called);
会不会像:
if (inStore){
return waiting;
}
else (
return called;
}
我不确定,因为我在执行此操作时遇到错误,我在 void 函数中使用它
您必须将 waiting
或 called
分配给 temp->status
变量而不是返回它,同样在 else
中您错误地使用了括号。整个事情应该是:
if (inStore)
temp->status = waiting;
else
temp->status = called;
我不确定你为什么要在那种情况下使用循环,因为没有必要使用循环。
问题在这里:else (
。将 (
更改为 {
,您的编译应该是干净的。
ternary operator 只是快捷语法中的 if-then-else
语句,赋值语句显示为单个 lvalue
。所以:
temp->status = (inStore ? waiting : called);
翻译成:
if(inStore == true)
{
temp->status = waiting;
}
else
{
temp->status = called;
}
请注意,您的语法没有任何问题(除了此处的 "("
:else (
)。在函数中,如果函数在离开前不需要清理,则最好使用 return
语句。
if(inStore){
temp->status = waiting;
} else { // there was a ( instead of a {
temp->status = called;
}