简体   繁体   中英

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() {
    //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. 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:

  1. A big operation is to be done
  2. The operation is repeated numerous times in the program

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

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