简体   繁体   中英

Can I use an if statement with a return value as a function argument in C?

I want to be able to pass by value with an if statement:

 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(); );

 }

Thanks for your time, and I am open to any other suggested approaches. I know I can accomplish this task by simply doing a bunch of if statements within the function itself. Was just curious if I could reduce the number of lines required.

I will answer with this construct which will surely get you in trouble.
Ie I recommend to read this, see how horribly ugly it is and then NOT do it.

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

It uses the ternary operator ?: . Which is used as condition? trueExpression: elseExpression condition? trueExpression: elseExpression .

Please use this instead, though it is not as "short".

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

Or use the proposal from the comment by David C. Rankin, especially if you end up doing this multiple times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM