Function inside loop or loop inside function? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Function inside loop or loop inside function?

I was coding with C++ the other day and I was wondering... What is more relevant, using a function inside a loop in main() or calling a function with a loop inside?

29th Mar 2018, 1:46 PM
Vlad Tronciu
Vlad Tronciu - avatar
4 Answers
+ 3
Depends upon the nature of the program and the function. Is the loop's purpose only relevant in that one spot? If so, then use a loop with a function inside of it. If you reuse this function in other places, will it always require a loop? If so, put the loop inside the function instead. Basically, point of functions is to allow you to reuse code without having to constantly rewrite the exact same thing in various places. So going by that purpose, code that you'd have to rewrite the same (but maybe with new input) should be placed in a function that you can reuse and if needed feed variables to as input of the function. Hope that helps! Best of luck to you Mars.
29th Mar 2018, 1:52 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 1
What do you mean for "most relevant"??? Either use depends on context
29th Mar 2018, 1:51 PM
KrOW
KrOW - avatar
0
It really depends on what you're trying to achieve... Functions fosters code reuse. Thus, if the function will be called later on in the program, go with the former. If the function only pertains to that loop, then keep it local.
28th Sep 2019, 2:18 PM
Efosa Igbinehi
Efosa Igbinehi - avatar
0
Vlad Tronciu Functio IN a loop
3rd Oct 2020, 9:54 AM
Avi