C++ is notorious for using functions. Usually you will include different files into the main .cpp file in order to make everything look cleaner. By using a function, such as a type void, it allows your code to:
1) Look cleaner, and the individual who may go back and look at this code knows how to find the usage of it easily,
2) Multiple use: Let's say you constantly have to output different numbers that are being added together, or something of that idea; this function can be constantly called and will dynamically change.
3) Main is small. This goes along with my first point, where it'll make everything more clean.
Now, the function type void is used because you will not be returning anything from this function. You are purely using the function that you included to print out a message; by this, I mean that you aren't returning a number back to the
int main()
portion of the program, therefore, type
void is used. Now let's say you wanted to add two numbers together and return them to your
int main()
, depending upon what kind of numbers are being added, depends on what type your function takes. Let's say you're adding numbers that are of type
double, and these are being added in a function called, hmmm, let's say
double addingDoubles(double num1, double num2)
. Here, we can look at the function prototype and assume two things, we are going to add two doubles, and we have the function as a type
double, because we have doubles going in, and we will have a double coming out.
Now, in the main program, you could call the function and return the number from the added doubles, like so:
1 2 3 4 5 6 7 8 9 10 11 12
|
int main()
{
double answer;
double num1 = 2.1;
double num2 = 3.4;
answer = addingDoubles(num1, num2);
cout << "The answer of our two numbers added together is: " << answer << endl;
return 0;
}
|
Now, this is entirely unnecessary, because we could simply add in main, and output there. However, we can use this addingDoubles in different places now.
The point I'm trying to make, is that whether you have a function of type
double or in your case, of type
void, it's purely what you're trying to return, and since your function doesn't require anything to be returned, you can use void.
Quick tip in my experiences:
Normally, any time I've coded large programs in C++, void functions are normally going to be used for input/outputs and reading and writing files.
If you have any other questions, just let me know.
Your friendly Computer Engineer,
fnx