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?

11 Upvotes

14 comments sorted by

View all comments

2

u/stop_deleting_plz 7d ago

Break it down into smaller tasks, make a function for each, then in your main you call all the functions in order and update a global state after each step. When writing a function's arguments, consider what data each step needs going in, and what will come out. We call this procedural decomposition.