[英]which one is good practice: using block of code in main or making function of same code?
Actually what i want to know is that should i use function oftenly for short code or put it inside main for eg 实际上我想知道的是,我应该经常将函数用于短代码还是将其放入main中,例如
main() {
//something something
if(condition)i++; //This is the code for which i want to make function
}
Or should I use it like this 还是我应该这样使用
void incrementi() {
i++;
return;
}
main() {
//something something
}
Which method is fast to execute, readable or in short what is good practice? 哪种方法执行起来快速,易读,或者简而言之,什么是好的做法?
Simone Pesotto has given the right answer. 西蒙妮·佩索托(Simone Pesotto)给出了正确的答案。 But I would like to explain the reason.
但我想解释一下原因。 Everytime a function is called, an Activation Record is created and placed on the programming stack, alongwith details of calling function, pointers to it, parameters passed, details of the called function, etc. This obviously takes time.
每次调用一个函数时,都会创建一个激活记录并将其与调用函数的详细信息,指向该函数的指针,传递的参数,被调用函数的详细信息一起放在编程堆栈上。这显然需要时间。 Instead, something as simple as an increment operation takes only one machine instruction which is far cheaper than creating a separate function.
取而代之的是,诸如增量操作之类的简单操作仅占用一条机器指令,这比创建一个单独的函数要便宜得多。 So functions are made when:
因此,在以下情况下会创建函数:
I hope this answer helps in enhancing your understanding. 我希望这个答案有助于增进您的理解。
i ++是一个递增变量的函数(如果您要这样做的话)。
in this case, the code being done only by a condition and an increase, I advise you not to write a function but bring back the line of code whenever you need. 在这种情况下,代码仅由条件和增量来完成,我建议您不要编写函数,而是在需要时返回代码行。 If you had more instructions, it is advisable to create a function to call every time you need then reusing that piece of code
如果您有更多说明,建议您创建一个每次需要时都调用的函数,然后重用该段代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.