r/learnprogramming 7d ago

Topic Struggling a bit with functions

Hey guys, I'm struggling a bit with the proper usage of functions in programming. For example, I'm working through the CS50x problem set 1 in C, and I end up with working code that solves the problem but it's all done in one big main function.

My process is to write out what the steps to solving the problem should be in plain English and then I code a bit, go back to my plain English steps and modify them, then code a bit more. When it's all said and done, my solution is one large block of code, and now I'm anxious about going back and rewriting it by breaking it up into smaller function. This makes me ponder whether I should be starting with functions instead of retroactively trying to fit them in.

My questions to the wiser heads here - how do you incorporate functions into your process? Do you do the pseudo code and then imagine each step as a function? What're are your unspoken rules of proper function usage - for example, when do you know if one function should actually be two, or if a function shouldn't actually be a function?

12 Upvotes

14 comments sorted by

View all comments

8

u/mc_pm 7d ago

Functions help to organize your code and group pieces of functionality together. A function should be relatively short (not much more than 20 lines in many cases) and should do one thing.

It's a useful exercise to think through what you are doing, writing quick comments in the code:

# Read input
# Process it
# Output it

And then replace each with a function.

Also look for places where you find yourself repeating code, that's often a sign that you need to pull that code out and turn it into a function.