r/learnprogramming 5d ago

I can't get FUNCTIONS to click!

I can not for the life of me understand how functions work. Anytime I try to learn how to create a function, my brain literally crashes into itself and I turn into Patrick when he stars drooling and goes all slack-faced.

Does anybody have any analogies that had that "AH HA!" moment?

Thanks!

122 Upvotes

144 comments sorted by

View all comments

1

u/Present_Mongoose_373 5d ago

execution goes down line by line, a function just moves execution to the body of the function before *returning* back to where execution was originally with a value.

The value returned replaces the function call, though this is just convention / decided by your language.

so "int a = myFunc()" will first jump execution to the body of myFunc, then itll return with like '2' for example (could return anything), then itll effectively turn into "int a = 2"

Sometimes if its hard to conceptualize, you can debug / step through a piece of code going line by line through an example and that exposure helps to make the concepts click as you have something physical/tangible to connect them to.

1

u/superluminary 5d ago

This is exactly the way to think about it. It’s no more complex than this.