【发布时间】: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