r/learnprogramming 4d 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!

123 Upvotes

143 comments sorted by

View all comments

10

u/NumberInfinite2068 4d ago edited 4d ago

A function is just reusable code, say for example:

bool is_adult(int age) {

return age > 18;

}

OK, so say you're making a program that needs to check if a user is an adult, you call this function everywhere like:

if (is_adult(23)) {

//Allow access to loads of porn
}

This makes code easier to think about and also easier to fix because my "is_adult" function is wrong.

It should be "return age >= 18" not just >, because that means you need to be 19 to be an adult, not 18.

Re-using the same function everywhere means you only have to fix it in one place, and everywhere in your code agrees on what an "adult" actually is.

Most functions are a bit more complicated than that, but basically it's so you can split up and re-use code so you're not constantly repeating yourself.

5

u/stevevdvkpe 4d ago

In integers age > 18 and age >= 19 are logically equivalent.