The point of a function is that it is used multiple times in a program, so it prevents duplicating identical code.
Re-using the same code multiple times can certainly be a good reason to make a separate function, but it is by no means the only one.
It can be a good programming practice to have a function called just once at the start of the program, and another called just once at the end.
Separating code into functions can allow the logic to be understood at a high level, such as:
The actual details of what takes place inside the function need only be looked at when there is a need to do so. Placing the actual code there instead of a simple function call could just add unnecessary clutter and make the program much harder to read and understand.
@ne555 I don't consider the ctor a function; it's more like a special case. You can't take the address of it or get a pointer-to-member for it, it can't return anything, and you can only call it on first initialization or with placement new.
However, I do agree that it is beneficial for code to be in a function even if it is only used once; I was trying to explain the more common scenario of code duplication though because it is easier to understand the logic behind it. At least, you will sooner notice typing code over and over again than you will notice not understanding the purpose of a code segment you wrote months ago.
@ L B this is just a practice code because im trying to grasp the concept of the void type. I tried making up a simple code while trying out some things i thought i could do. so is it possible to actually do what i tried to do with the code i created. because i put the '&' sign behind the variables of the first function "void title (int &firstname, int &lastname)" but its not working all it shows now is the lastname variable (it doesnt even show the cout << "You entered" << firstname << "," << lastname;) i dont know why it only shows the lastname variable. Any help.
well honestly i have created a practice code to practice the void type, but i have to do a project that calculates the Grade point average of 3 grades entered. my professor told the class that we have to create 4 functions and 1 had to be a void this is what i have created so far but im still tryin to use do while to keep executing until you exit the program.
int g1 (int grades1)
cout << "grade 1 : ";
cin >> grades1
int g1 (int grades2)
cout << "grade 2 : ";
cin >> grades2
int g1 (int grades3)
cout << "grade 3 : ";
cin >> grades3
//i have to use a void but i dont know what to use yet
int grad1, grad2, grad3;
//now here is where im having trouble im trying out some different things
//but its not working i just need an idea or some advice please.
i dont know how i would loop these functions although to be a function would it need 2 variables in the parameters?
but any way i wanted to understand void completely to then try and create my homework code. but its confusing. im new to this remember im still in basic stuff.