0
Difference between, or reason for, a function returning a value verses one that does not return a value.
Im not sure I understand the reasons behind functions that return a "value": ------------------- int main() { // some code return 0; } ------------------- ...verses one that does not return a value but "outputs" something instead: ------------------- void printSomething() { cout << "Hi there!"; } ------------------- What is a "value" if it isnt simply an output ie cout << "Hi there"; #Confused
2 Antworten
+ 5
Functions with void return type dont return any value. So, there will be no output if you try printing a function with no return type.
+ 2
There are many ways to think about the return of a function, and it all depends on how you want your code to look or the way you prefer to do it. Returning a value is used to maintain whatever value was achieved within the function, so that it can be used a level above. Here are two ways that I think describe what I'm talking about:
1.
int value = someFunc(); // of course this function returns an int.
2.
int value;
someFunc(&value); // passing by reference allows you to change value within the function
// and, for this case, someFunc would be of a void return type
So it all depends on whether you want to pass by value or pass by reference. And if the value of a variable doesn't need to be saved between functions, it would always be void. Much like the output example you gave.
I hope this helps. Happy coding :)