我可以使用带有返回值的if语句作为C中的函数参数吗?

问题描述 投票:0回答:1

我希望能够通过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语句来完成此任务。只是好奇是否可以减少所需的行数。

c function pass-by-value
1个回答
0
投票

我将以这种结构回答,这肯定会给您带来麻烦。即我建议阅读此书,看看它有多可怕,然后再不做。

function((x==1)? otherFunction1() : otherFunction2() );

它使用三元运算符?:。用作condition ? trueExpression : elseExpression

尽管不是“ short”,但请使用它。

  if (x==1)
  { function( otherFunction1() ); }
  else
  { function( otherFunction2() ); }

或使用David C. Rankin的评论中的建议,特别是如果您最终多次这样做。

© www.soinside.com 2019 - 2024. All rights reserved.