Why solve()?

Why many people use this technique :- creating a function solve() inside main and then solving whole problem inside solve()?

1 Like

Well, I can’t really speak for the general consensus but I use it when I need to break out of the inner nested loops without using two breaks and a flag, I just return the ans.
Likewise, when there’s a corner case in the beginning you either need to use exit()(in the main) or return the ans. Not much except for this.

8 Likes

Like @qaseem_hasan, I use it for an early return when I’ve already computed the answer.

Also, I usually have a solveBruteForce and solveOptimised, which makes it easy to compare the results from the two.

13 Likes

As most people would agree, that is often needed when you want to report the answer and go to the next test case, jumping all the code in between. You can either use goto , which is rather unattractive and has it’s own problems. A separate function makes it easier to quit the test early.

3 Likes

:thinking: HMMM…
I must admit. That’s pretty clever. I should start using that.

4 Likes

I generally use solve because it makes my code clean and more clear. Doing everything inside main function makes it look really ugly if the code is long. (For short questions I prefer using the main function)

One question:: I’ve seen many people name arrays as dp[] in their code. Is it bcuz the question is related to Dynamic Programming or just generally???

2 Likes

Cause dp

I can use continue instead of goto

I name all my dp arrays as dp[], because when I first started solving some dp problems altogether it was first instinct to start the code with an int dp[n]. So it just catches up.

However if you see some cleaner codes (like the setter’s solution or the tester’s solution) they give proper names to their dp array.

1 Like

this is clever, i used to break through all the nested loops when i had computed my answer

It’s always a good practise to make your main function (int main in C,C++) to make less clumsy.

2 Likes