Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以在C中使用带有返回值的if语句作为函数参数吗?_C_Function_Pass By Value - Fatal编程技术网

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

我可以在C中使用带有返回值的if语句作为函数参数吗?,c,function,pass-by-value,C,Function,Pass By Value,我希望能够通过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();

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

我将用这个结构来回答,这肯定会给你带来麻烦。 也就是说,我建议读一读这篇文章,看看它有多么丑陋,然后不要去做

function((x==1)? otherFunction1() : otherFunction2() );
它使用三元运算符?:。哪个用作条件?trueExpression:elseExpression

请改用这个,尽管它没有那么短

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

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

减少所需行数从来都不是一个优势,尤其是如果它降低了可读性而没有实现任何好处。int rtnfunctionint x{如果x==1返回其他函数1;否则返回其他函数2;;然后在main中调用return rtnfunctionx;。或者简单地在main中返回x==1?其他函数1:otherFunction2;有一种方法可以减少代码,并对现有代码进行最小的更改。但是,当任何人y试图在三周内阅读您的代码。我的缺点是,函数中应该有一个int参数。我知道这不一定是好的约定,我很少使用它,仅在我现在正在进行的项目中使用它会很方便。我非常感谢。在我做过的数千次类似这样的问题中,我当然不会使用它条件语句的返回值传递到函数中,但现在对我来说很方便。再次感谢!事实上,函数参数列表中的三元值本身并不坏,只要您了解函数已经提供了所需参数类型的返回。这可能不是推荐的或最可读的方式,但是这当然是一种合法的方式。