doesn't it actually returns the "first" and "second" string when we call the function??? |
No. It
prints the first and second string. It does not return them.
Printing outputs something to the screen.
Returning gives information back to the calling code.
Return values are used for when a function has output (not
screen output, but computation/logic/code output). Example, let's say you have a function that cubes a number:
1 2 3 4
|
int cubeit(int num)
{
return num * num * num;
}
|
Here, the return value is 'num' cubed. Note it doesn't print anything to the screen... it's just "returning" the value.
The returned value can be used by the code that calls this function:
1 2 3 4 5 6
|
int main()
{
int val = cubeit( 5 ); // assigns the returned value to 'val'
cout << val; // prints '125'
}
|
The type (in this case, int) determines what type of value the function returns. Here, we are return an int, but you can also return a string, or any struct, class, or any other variable/object type.
A
void
function indicates that the function does not return any value. And therefore it would be illegal to try to assign the return value to something:
1 2 3 4 5 6 7
|
void noreturn()
{
}
int main()
{
int foo = noreturn(); // error, noreturn doesn't return anything -- it returns void
|
@ Chevril:
Your example is confusing... I would expect a function named "PrintName" to print the name, not return it.