I have seen in many people's code that they use a solve function instead of writing the logic in the main function. What advantages it has over writing the code directly in the main function?
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | Dominater069 | 154 |
8 | awoo | 154 |
10 | luogu_official | 150 |
I have seen in many people's code that they use a solve function instead of writing the logic in the main function. What advantages it has over writing the code directly in the main function?
Название |
---|
The use of the function solve() does not affect the running time of the program. But it makes the code more readable.
I don't use cause functions take memory.
https://stackoverflow.com/questions/21735407/do-functions-occupy-memory-space
Classic case of premature optimization.
That is not a consideration you should be having, pretty much ever.
Allows for easier switching between single testcase and multiple testcase problems. For example:
You can use
return
to easily and quickly exit the current testcase.By far the best reason. Imagine having something like if specific case, then continue the loop. And now you have a bunch of such cases. Your code would be pretty ugly and filled with just exiting the loop.
You don't have to worry about using continue in the testcase loop when you're done printing the answer to stdout halfway to the code, you can just return after that.
One important characteristic of high-quality code is orthogonality. (I'm not telling you to make your code more vertical, but more clearly.) If you want to write orthogonal code, it is often more efficient to encapsulate statements within functions, making debugging more convenient as well.
Additionally, the best part is that the "return;" statement can directly jump to the next test case without the need for control variables or goto-like statements.
Moreover, some programmers try to have fewer statements within their main function to make the logic clearer, specifically for their own reading purposes.
for me , the reason I use solve() is because I can just return in the function whenever I want to and preceed to the next testcase , that makes it easy to exit a testcase , doing it in main would require multiple variables and ifs so it is just convenient