Ok, let's just try to explain this one step at a time.
The simplest function example I can give you
1 2 3 4 5 6 7 8 9 10 11
|
#include<iostream>
void printHello(){
std::cout << "Hello";
}
int main()
{
printHello();
return 0;
}
| |
The reason that function used void was because we didn't want to return anything. It would be a waste of resources making that function an int, a float, a string, etc.
In this case the compiler sees the function at the top, get's what it's supposed to do with it, then in
int main()
sees it being called and refers to the instructions under that function. Whenever you call a function you simply type the name of the function
printHello
then parameters
()
. In this case we don't have anything we are passing into the parameters, so it's just
printHello();
Prototyping a function is the same way as far as how you write it out except for your parameters
printMessage(std::string message);
Then somewhere else we can actually define the function (which is another difference, don't try to define your function in another function, either define it globally or in a class)
1 2 3
|
void printMessage(std::string message){
std::cout << message << std::endl;
}
| |
Entire program
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include<iostream>
#include<string>
void printMessage(std::string message);
int main()
{
printMessage("Here's a message");
return 0;
}
void printMessage(std::string message){
std::cout << message << std::endl;
}
| |
The prototype at the top allows the function to be defined after
int main()
rather than before. However, this is just a simple example of the power of prototyping. You'll use it A LOT more once you start handling header files. The
(std::string message)
is like a placeholder saying
"When this function is called, a string will be passed in here"
If you don't understand just PM rather than drive everyone crazy. Programming isn't just something you spend 15 minutes here and there picking up stuff. It can be a very grueling activity and takes a lot of invested time to get good at. (I've been at it for about 6 months and honestly still feel like a complete noob compared to the majority of people on here, despite spending A LOT of time programming) There's no easy around this. I think a good programmer will read a lot, think a lot, have a lot of patience, among other things. If this isn't for you or you're one of those people getting into programming because you heard it pays good money, you need reconsider your career choice possibly.