Hello everyone.. I know it's a very stupid question, but I can't understand what exactly is the purpose of "return"?
Hello everyone.. I know it's a very stupid question, but I can't understand what exactly is the purpose of "return"?
It basically returns the value of a function
think of it this way:
when you get in the car and go somewhere, it's equivalent to calling a function. it would be highly unusual to never come back, so when you come home, you're returning from that function call. sometimes you leave to go buy something from the store. when you come home with your merchandise, that's like returning a value.
Code:/* a place to hang out */ void aVoidFunction() { /* we don't need to explicitly return, but just for the sake of conversation, we will */ return; } /* a place to get integer values */ int anIntFunction() { /* because our function is expected to send back a value, we have to explicitly tell it what to return */ return 0; } int main() { /* go somewhere, just to hang out */ aVoidFunction(); /* we came back */ /* go somewhere to get an integer value */ int someInt = anIntFunction(); /* we came back with our integer value in hand */ /* main() always must return an integer value 0 = success */ return 0; }
Ok, but return is not visible like printf() or usable, right?
So, we use it for typical reasons?
i dont know what exactly you mean by typical, but it is highly useful when you create functions to perform specific tasks and need a value that the function computes in another part of your program
it's also useful for stopping the execution of a function before its natural end. let's say it encounters some sort of problem halfway through, and if you continue, it will cause undesired behavior. you would then return, possibly with an error code as the return value, to avoid continuation in the face of the error.
something like this:
Code:int someFunction(int aParameter) { if (aParameter < 3) { return -1 /* aParameter must be at least 3 */ } /*continue function here*/ return 0; }
Ok.. But can we use "return", in order to store data to a variable? For example, something like:
What would happen then?Code:int func(int a) { if (a == 5) return (a = 2); else return a; }
Why don't you try it and look at the result?
Bye, Andreas
Nothing happened.. then I printed out "a" and it printed what I gave to it.. When I gave to the input 5, shouldn't it print 2?
input: 5Code:#include <stdio.h> int func(int a) { if (a == 5) return (a = 2); else return a; } int main(int argc, const char * argv[]) { int a; scanf("%d", &a); func(a); printf("%d", a); return 0; }
output: 5
Notice that you did not use the return value of func in main.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
How do I do that?