I am reading a chapter about functions in a beginner's book for C++ and have two questions.
1) Should a function be declared at the beginning of the code and defined at the end or should the function be completely defined at the beginning?
#include <iostream>
void myfunction(); // function declaration
int main(){}
// function definition
void myfunction() {std::cout << "Hello World from a function.";}
or
#include <iostream>
void myfunction() {std::cout << "Hello World from a function.";}
int main(){}
Intuitively, i would have used the last variant because its more compact. Is there a good reason why one should use the first (longer) variant?
2) When should an argument of a function be used as value or reference? I do not see what advantage there should be in using the argument as reference.
#include <iostream>
void myfunction(int& byreference)
{
byreference++; // we can modify the value of the argument
std::cout << "Argument passed by reference: " << byreference;
}
int main()
{
int x = 123;
myfunction(x);
}
If i would have used myfunction(int byreference) instead, i would get the exact same result. So if i pass the argument as a value, i can still modify it.