+ 2
What do return and void exactly do? And what is their difference?
I've been trying to learn c++ and right now im at the function part but I have been having trouble understanding what void and return exactly do and what their difference is.
9 odpowiedzi
+ 8
A function with no return type, is a void function. "Void" basically signifies "No type", so you can't return anything. This is used when you don't have to return anything from a function, e.g. printing stuff.
void example1() {
std::cout << 39;
}
A function with a return type is declared by specifying the data type of the return value. This value is returned to the function caller, useful when you want the function to perform some kind of computation and obtain the resulting value.
int example2() {
return 39;
}
When you are calling them, the difference is obvious.
int main() {
example1(); // prints 39
example2(); // 39 returned, but not printed
int i = example1(); // error, nothing returns from function call.
int j = example2(); // 39 stored in j
}
+ 6
Matthias return does not always have to be at the end of a function although it may be good practice to return from close to the end to improve maintainability of the code.
+ 5
return is used at the end of a function.
It is used, to return a value, as it name already tells.
What type of value should be returned, stands always in front of the function.
Example:
int foo(){
return 2;
}
When calling foo(), it will return the integer 2.
int x = foo(); // x is now set to 2
Sometimes, you don't need to return anything. This can have different reasons. The function might by only used for printing or makes changes directly on the original memory places (you will come to call-by-reference vs. call-by-value later in the course).
So for now, just think of the printing example:
void bar(){
cout << "This is printed in bar";
}
As you can see, there is no return statement at the end of the function.
However, the return type must be written at first, right before the function name.
Since there is nothing to return, we use void.
I hope it is more clear now :)
+ 3
void is used when you are not required to return anything from the function to the caller of the function.
+ 3
I am not clear about the question. But I am going to reply in reference to c++. In c++, 'return' is a keyword which marks the end of flow within a function block. When compiler encounters 'return', it generates the code to return from current function and clearing up of current function 's stack frame. Any statements past 'return' will not be executed. It doesn't call any OS related call, it simply copies(if needed) return value to destination & restores stack pointer to earlier stored value. Thus marking the storage used by current stack frame as 'free' which can be used in any subsequent calls..
Yeah..That's what I know❤️🙌
+ 2
Thanks to everyone, I understand it now! 😀
+ 2
return returns the value
void has no return value