if youre saying its just the way you learned then perhaps someone should explain return types, but mostly because i like giving lectures.
generally when you write a function youre going to want to get some kind of data back from it, unless its just a function to print something like you made in the above code, which is fine. however lets say you want a function to add two numbers then you would need to change the return type. if it was void, your function would perform the calculation but wouldnt give it back to you as can be seen here:
1 2 3 4 5 6
|
void addNums(int num1, int num2)
{
int sum = num1 + num2;
return;
}
|
if we wanted to actually get the sum of the two numbers then we would have to change the return type from "void" to "int" so the function would then look like this:
1 2 3 4 5
|
int addNums(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
|
two things to note about return types:
1. if your return type isnt void then you MUST return something.
2. whatever you return must match the return type, that is to say you couldnt return 2.3 if the return type was int or else you would get an error. however if you changed the return type to double it would function (no pun intended) perfectly.
also note that whenever returning a value it will be lost unless you store it in a variable. using the above mentioned function to get this result your main function would look something like this:
1 2 3 4 5 6 7 8 9 10
|
int main(void)
{
int num1 = 3;
int num2 = 5;
int sum = addNums(num1, num2);
cout << sum;
return 0;
}
|
here its storing the sum of num1 and num2 (8) in the sum variable and then just printing it ofcourse. alternatively if you just want to print the value you could do something like this:
|
cout << addNums(num1, num2);
|
:o how interesting that the return type of main is int and it happens to return an integer value (0).... omg!
note however that you cant return an array, but you can still return a pointer. be careful though because if its a pointer to an array defined in the function youll run into trouble because the array will be deleted at the end of the function call :(
obviously theres a lot more intricacies to return types and a HELL of a lot more to functions but hope dis helped <33 :)