【问题标题】:Can I use an if statement with a return value as a function argument in C?我可以使用带有返回值的 if 语句作为 C 中的函数参数吗?
【发布时间】:2020-02-18 04:49:07
【问题描述】:

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

【问题讨论】:

  • 减少所需的行数从来都不是优势,尤其是在降低可读性但没有任何好处的情况下。
  • int rtnfunction(int x) {if (x == 1) return otherFunction1(); else return otherFunction2(); ); 然后在main() 调用return rtnfunction(x);
  • 或者只是在main() 所以return x == 1 ? otherFunction1() : otherFunction2();
  • 有一种方法可以实现“更少的代码”和对现有代码的最小更改。但是,当有人试图在三周内阅读您的代码时,这会让您与任何老师、朋友、同事甚至您自己陷入困境。
  • 我的错,函数中应该有一个 int 参数。我知道这不一定是好的约定,而且我很少使用它,只是在我现在正在从事的项目中使用它会很方便。

标签: c function pass-by-value


【解决方案1】:

我会用这个结构来回答,这肯定会给你带来麻烦。
IE。我建议阅读这篇文章,看看它有多丑陋,然后不要这样做。

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

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

请改用这个,虽然它不是“短”。

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

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

【讨论】:

  • 我非常感谢。在我不得不做这样的问题的数千次中,我当然不会使用条件语句的返回值来传递给函数,但现在对我来说很方便。再次感谢!
  • 其实函数参数列表中单独的三元也不错,只要你理解函数已经提供了所需参数类型的返回。这可能不是推荐或最易读的方式,但它肯定是一种“合法”的方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-16
  • 1970-01-01
相关资源
最近更新 更多