r/cpp_questions • u/Sharp_Alfalfa_1571 • 1d ago
SOLVED Whats the point of functions?
Im new to c++, and I wonder why is there even functions other than the main one, why cant everything be in the main function?
22
u/DasKapitalV1 1d ago
Try to build any complex software in any main function from any language.
You will probably start to ask yourself, why do I need to keep repeating this peace of code everywhere? Or, this file is starting to get too big to work with
5
11
u/Alduish 1d ago
first reason would be to separate code that will be reused multiple times (everything in main is rapidly unreadable and a pain to maintain)
second reason would be because you don't only make programs in C and C++ but also libraries where "everything in main" wouldn't really work, unless you want to imitate a bash script with pipes everywhere to link input and outputs of multiple programs.
That's the two reasons I think of but there are probably many others.
6
u/JonathanCRH 1d ago
This is a bit like asking what the point of pronouns is. Yes, you could just repeat a name or description of a thing every time you want to refer to it, but itâs a lot easier if you can just say âitâ every time after the first one.
4
u/Independent_Art_6676 1d ago
functions are possibly the most important concept in c++.
As others said, you can use them to reuse code, type it once, use it often. A simple example is anything in the c++ math library, like sqrt. If you didn't have a built in sqrt, and you didn't have a function for it, you would be forced to insert a for loop to compute it EVERY SINGLE TIME you needed one.
functions do much more than that, though. They are used in large, complex user defined types (lets just call them objects for now) to help define the behaviors of those objects. For example if you had a bouncing ball in your pong game, it might have a color, a position on the screen, a velocity that tells where it will go next, and more. Such a complex object will use functions to do things, like reset it to a default starting position or make a sound when it hits a wall.
functions also can be used to manage data. A function with a static variable can update its value using protections to prevent invalid updates and return the value (or a protected copy of it) as a way to have a "much safer" global variable (one of several ways to do that).
functions can perform complicated solutions using recursion, which cannot even be done in main (its illegal to call main from inside main). Recursion is the idea that you can solve a problem by solving the same problem with an easier input until the input is so simple the answer is just known, and back filling the known answer solves the previous one all the way back up the chain to solve the original question. That may be too much to get into but its another place functions are important.
Many more things functions can do are difficult to explain (they rely on advanced c++ that you haven't seen yet and is difficult to explain at your level) but there are quite a few other ways they are useful and necessary to get things done in c++.
2
u/Ordinary_Let8356 1d ago
The building block of programming. Our lives would turn into us just waiting and waiting and waiting. A simple banking procedure would take hours.
1
1
u/Thesorus 1d ago
That's why I hate when people try to learn a (any) programming language before learning programming.
sorry to be brutal.
→ More replies (1)
3
u/MyTinyHappyPlace 1d ago
I thought the same thing when I was a kid, starting with QBASIC: Why can't I just do everything with GOTOs?
The answer is: It's way, way more comfortable using functions if you want to get stuff done. Make a sound? Call a function! Make that sound again? Call the function again. Of course you can avoid functions, but you will drown in spaghetti code in no time.
4
u/vsoul 1d ago
I remember when I moved from global variables and GOTO into SUB (also started in BASIC). I didnât get it at first either, and then I was enlightened
3
u/MyTinyHappyPlace 1d ago
It really was a thrilling concept to me. If I remember correctly, the editor even handled the SUBs differently
1
u/Independent_Art_6676 1d ago edited 1d ago
I learned them on the hp-11C, my first 'programming'.
It had the letters A-E and digits 0-9 that could all be functions. a-e could be executed directly on the screen value (and the machine's call stack) as if buttons on the calculator, giving you a lot of user defined power (for the era). Guess I am that guy... I didn't pick up basic until messing with excel much later on... by then I knew pascal and some c++. Only one who never had a 2e.
2
u/mgruner 1d ago
it can be, it's just a bad idea. There are many reasons to have functions:
- avoid duplication: if you need to perform the same operation over the same type of data more than once, you can create a function for it instead of repeating the same operation in several locations
- improve readability: it's is absolutely horrible and hard to understand a very long and convoluted function.
- reduce complexity: dividing in function forces you to divide the problem in smaller problems, which is always desirable.
- reusability: functions can live in a shared module that other applications can use (a library for example)
- ease of testing: it's way easier to test and exercise all the paths of a simple, well defined function.
- decoupling / individual responsibilities: having your functions do one thing (responsibility) is better for your design. Failing to do so makes your code harder to maintain, modify and extend.
In general, this is true for any language. As you progress in your career, you'll notice that it's not enough for it to "do what it needs to do" and "do what it needs to do while being easy to maintain, scale and change". Coding was never the interesting part (Agents can do that pretty easily). Designing an app that is readable, scalable, extensible, modular... that's where the art is
1
u/herocoding 1d ago
Think about functions the language C/C++ have by default, like "sin()" or "qsort()" - you can just call them, re-use them, provide different arguments.
Without the ability to have functions/methods/procedures you would need to write (and copy) the same code whenever you need it (again).
1
u/Unknowingly-Joined 1d ago
Imagine your program had two arrays and it needed to sum up the elements in each of them and print out the sums. If everything was in main, you would have two for loops, each one iterating over the contents of one of the arrays and printing out the results. With functions, you can write one function that does the summing/printing for âany arrayâ and then just call it twice, once for each array.
1
u/Ikitoi 1d ago
Reusability - suppose you have some expression at line 4 (in the main function), if you'd need the same expression five more times on different lines, you'd repeat yourself by writing them out explicitly again. Hence, function help to group statements together so that when next you need to use them, you just need to call the function.
Modularity - Writing every statements in a single main() function will lead to a large file. Function helps with modularity (breaking large files into multiple maintainable chunks seperated in different file). You can add math functions like sum(), mul(), div(), etc... into a math.cpp file and call it whenever you need it I'm the main function.
Testability - There is something called unit testing, whereby you test a single aspect (unit) of the whole codebase to see if it does what it is intended to do. Having functions made this very easy, all you have to do is to pass in the argument to each functions (if need be) and test them to see if they actually performs and returns the desired result. Having lots of statements in one main() function will be very hard to test In this case because you can't know which part of the program is broken as you'd have to test everything as a whole.
There are more reasons, these are just the first ones that come to mind.
Hope my explanation helps.
1
u/Total-Box-5169 1d ago
We write functions out of convenience, to make the code easier to maintain. You can have everything inside of main. However you will have to call functions to be able to use the operative system features, and even that is optional if you write your own code to deal directly with the hardware. That is usually only done by people working by the hardware designer/manufacturer, who write driver code that is called by the operative system.
1
u/no-sig-available 1d ago
why cant everything be in the main function?
It can, as long as it is small and you write all the code yourself.
Now suppose you work in a small team of developers. It would be really inconvenient for all of you to put your code in main. How would you compile and test your code while someone else is adding their code?
It is much more convenient for each person to write one (or more) functions, that they can then also test separately. It is not uncommon for main to only contain calls to other functions, and nothing else.
1
1
u/mredding 1d ago
The largest C++ application I supported was 12m LOC. Can you imagine all that in one function, one file? That one file would be ~600 MiB.
1
1
u/Raknarg 19h ago
You absolutely could, but once your program starts getting big enough you run into 2 issues:
a) The code becomes unreadable and you can't compartmentalize things. Its easier to read "blobularize_doohickey()" to know that this is where the doohickey gets blobularized, and if you want to know how the blobularization works you can go read that function. As a sidenote to this, you get some documentation for free this way. Just by attaching some code to a name, you've added context for the user that invoking this function blobularizes doohickeys, you didn't have to read the code to figure out that's what it was doing.
b) You start repeating yourself. Very often you'll come across repeated patterns where you either need to do the exact same operation or the same operation against different arguments/values. Instead of writing the code block twice, you throw it into a function and call the function twice.
1
u/New_Magician6884 1d ago
The best way to learn is through pure practiceâand out of NECESSITY. Donât wait for someone to feed you dry theory; go to ChatGPT or some other AI and build your code piece by piece. When you encounter a NECESSITYâlike needing a specific functionâyouâll finally grasp its actual purpose. Of course, all sorts of fools will inevitably show up, ready to recite the same old, dry, textbook definitions.
7
u/FounderOfYou 1d ago
so we don't have to write the same code over and over again for specific tasks. at your level, you won't probably have uses for functions but when you make big projects they are almost essential
also from where are you learning cpp?