简体   繁体   中英

I don't understand what's return for

I've recently started to learn C++, and I was doing well so far, until I came to function declaration and calling. What I don't understand exactly is what return is for and why every function requires it.

Also, why do you need a function type? For example

int xamplefunc(){}

What is the int type for?

EDIT: Well,i'm not sure if i get it. What exactly does return do? What really happens behind the curtains? Does the calling function store the return value as a variable, or what?

its like the

return_type  function_name(parameter list)
  {    
     //body of the function     
  } 

The return_type specifies the type of the data the function returns. The return_type can be void which means function does not return any data type. The function_name is the name of the function. The name of the function should begin with the alphabet or underscore. The parameter list consists of variables separated with comma along with their data types. The parameter list could be empty which means the function do not contain any parameters. The parameter list should contain both data type and name of the variable

For example,

 int factorial(int n, float j)

Good Read

as by @DeadMg http://www.wide-language.com/cpptuts/functions.html

Maybe it helps you to remember how a function is defined in mathematics: There a function f(x) takes an argument x and returns a value which you can calculate from x. For example the function sin takes a real number and returns another real number, the sine of that number.

C++ functions are models of this. For that reason, when you define a function, you must tell the compiler both what arguments of which types the function takes (this is the argument list in parentheses) and what type of value it returns (this is the return type, which you called "function type" above; note that in C++, the term "function type" is used for something different).

So when you want to write a function which calculates the sine in C++, you'd do it as follows:

double sin(double x)
{
  // code to calculate the sine of x
}

However now you get to another problem: Unlike in mathematics where you typically write the function as single expression, in C++ you'll write some list of statements to execute. That list of statements will typically manipulate many values. So how do you tell the compiler which value is actually the one which should be returned as the sine of x?

The answer to this is the return statement. So your function might look like this:

double sin(double x)
{
  double result = 0;
  // code to modify result so finally it contains the sine of x
  return result;
}

Note, however, that return not only tells the compiler "this is the result to return" but also "when you get to this statement, you're finished, return to the caller now. "

So consider for example the following code which uses special handling to detect NaN and infinite values (for simplicity I'll assume that functions is_bad and getnan have been written for this purpose):

double sin(double x)
{
  if (is_bad(x))
    return getnan(); // when this is executed, the function *immediately* returns
  // if we get here, we therefore know the value x is a regular number
  double result;
  // calculate the sine
  return result;
}

Now sometimes you want to write just some code you want to get executed on a call, but don't need to return a value. Some other languages use a separate construxt for this, but C++ models this difference by just introducing a type for nothing. That type is void . In that case, you don't need an explicit return statement because there's nothing to return anyway. For example:

void say_hello()
{
  std::cout << "Hello!\n";
}

Note however that the return statement can still be useful for early returns, which is why it is allowed in that case, too:

void say_hello(std::string to_whom)
{
  if (to_whom = "satan")
    return; // I don't say hello to satan!
  std::cout << "Hello " << to_whom << "!\n";
}

Finally, a remark about the main function: This one also has a mandatory return value of int . With that return value, you tell the caller of the program whether your program finished successfully or an error occurred. So you could write (using constants defined in <cstdlib> )

int main()
{
  return EXIT_SUCCESS; // I've succeeded in doing nothing!
}

or

int main()
{
  return EXIT_FAILURE; // I have no idea what I was supposed to do,
                       // so I couldn't do it :-)
}

Note that instead of EXIT_SUCCESS one can also return 0 to indicate success (indeed, typically EXIT_SUCCESS just has the value 0 )

Now main has an additional rule that, unlike any other value-returning function, you can omit the return statement. If you do so, the effect is the same as if you had written return 0; at the end of the function.

What you call the function "type" is the return type of the function. It means that a call to the function returns an object of that type. And the return statement is where the function does the returning.

int random() {
  return 4;
}

This function returns an int . You can call it to assign a value to an int:

int n = random();

You have a Banking system. You want to let users request their balance. You implement a getCurrentBalance method. You will need a return type to give back their balance once you calculate it in the method body. You will also need an input parameter, their account number maybe:

double getCurrentBalance (int AccountNo)
{
   double balance = //Check balance for AccountNo in Database or whereever
   return balance; 
}

Don't look too much into the types I've used please. I know double is not the best for currently.

return balance; 

That must match our return type ie double. You can however return to something that is implicitly cast to a double. You could return int balance if you so wished (loosing precision of course).

when you call a function, you sometimes want to get something back, for example, you can call a function which does a simple calculation (2x2), and you want the answer. if there was no way to return an answer, you would need to resort to all kinds of work-arounds.

what you called "function type" is actually the type of the answer you expect to get from the function. In your case, you expect the function to return a value of type int (for example a number)

if xamplefunc was defined like such:

int xamplefunc(){
    return 2*2;
}

you would expect to get back 4 when you call the function.

The return type has to be known to the compiler in order to know the bitsize of the variables of the given type, which registers are best suited and to infer the memory addresses to which to read and write to as well as the address intervals for optimal allocation.

A function may not return a value (void). If it does returns a value, the value must be obtainable by the caller of the function.

The called function puts its return value at a location that is known to the caller-function and which the caller function must be able to access. The return value is put in memory before the ret instruction is executed:

For instance. Given the following function:

int xamplefunc(int x, int y)
{
   return x + y;
}

it will be assembled on an x86 machine with the MSVC compiler to:

:_xamplefunc@8
push ebp
mov ebp, esp
mov eax, [ebp + 8]
mov edx, [ebp + 12]
add eax, edx
pop ebp
ret 8

or via LLVM on an x86 machine:

define i32 @xamplefunc(i32 %x, i32 %y) nounwind uwtable readnone {
  %1 = add nsw i32 %y, %x
  ret i32 %1
}

Note : The order and registers used may differ from compiler to compiler and versions, a useful property in software forensics.

Some languages (eg Coffeescript) also provide an implicit return, by returning the value of the last declaration within the function declaration.

int xamplefunc(){}

Function that returns value of type int and receives nothing. This code is incorrect, since there is no return , if there is no compilation error - some garbage will be returned.

after doing some operations, often u need to return the calculated new values to the function caller. suppose i want to add two numbers & return addition to caller, then i can write function as

int add(int x,int y)
{
return X+y;
}

here return statement tells that , ur returning int value.
if u don't want to return anything ,then u simply use return type void as follows

void add(int x,int y)
{
//some statements;
}

The Function type is aptly said return type . It is called so because it's return back the specified type in you're example

     int xamplefunc(){}

an integer is returned back to you...

for a detailed explanation check the following link http://www.learncpp.com/cpp-tutorial/74a-returning-values-by-value-reference-and-address/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM