Alright, so on my way through learning c++, I noticed that functions are done two different ways, but I cannot find if there are differences, or if they are just preferred ways of doing functions.
Here I have two different simple codes done in different ways.
The first way declares the entire function at the top:
Code:
#include <iostream>
using namespace std;
int factorial(int num)
{
int starter;
int total = 1;
for (starter = 1; starter <= num; starter++)
{
total *= starter;
}
return total;
}
int main()
{
int num;
cout << "Please enter a number greater than 1!" << endl;
cin >> num;
if (num <= 1)
{
cout << "Please use a number GREATER than 1." << endl;
}
else
{
cout << "Function returned: " << factorial(num) << endl;
}
system("PAUSE");
return 0;
}
This second way uses what I've read as being a "Prototype" and then has all the information at the bottom of the code.
Code:
#include <iostream>
using namespace std;
int factorial(int prototype);
int main()
{
int num;
cout << "Please enter a number greater than 1!" << endl;
cin >> num;
if (num <= 1)
{
cout << "Please use a number GREATER than 1." << endl;
}
else
{
cout << "Function returned: " << factorial(num) << endl;
}
system("PAUSE");
return 0;
}
int factorial(int num)
{
int starter;
int total = 1;
for (starter = 1; starter <= num; starter++)
{
total *= starter;
}
return total;
}
Both of these codes work the exact same way, however, the prototype seems useless, as I could just replace it with the entire function that I want. Not only that, but with the prototype, my (int prototype); seems to never have any use.
So yeah, I'm lost here. Can anyone please explain the differences, if any in this? Do I NEED to use a prototype, or can I just do it the first way that I have it in all cases and still have it work just fine? Thanks in advanced!