我希望能够使用 if 语句传递值:
void function(int x){
// do
}
int otherFunction1(){
// do stuff
}
int otherFunction2(){
// do other stuff
}
int main(){
int x = 1;
function(if (x==1)
return otherFunction1();
else
return otherFunction2(); );
}
感谢您的宝贵时间,我愿意接受任何其他建议的方法。我知道我可以通过简单地在函数本身中执行一堆 if 语句来完成此任务。只是好奇我是否可以减少所需的行数。
最佳答案
我会用这个结构来回答,这肯定会给你带来麻烦。
IE。我建议阅读这篇文章,看看它有多丑陋,然后不要这样做。
function((x==1)? otherFunction1() : otherFunction2() );
它使用三元运算符?:
。哪个用作条件? trueExpression : elseExpression
.
请改用它,尽管它没有那么“短”。
if (x==1)
{ function( otherFunction1() ); }
else
{ function( otherFunction2() ); }
或者使用 David C. Rankin 评论中的建议,特别是如果您最终多次这样做的话。
关于我可以在 C 中使用带有返回值的 if 语句作为函数参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58497439/