Return


#1

In the sample program “Degrees” in chapter 5, I know it has something to do with freezeInC = 0, but I don’t understand how the computer knows the variable cel = 0. I’m having trouble wrapping my head around how we took the return value of FahrenheitFromCelsius() and assigned it to the freezeInF variable of type float. Can anyone expand on this? Thank you!


#2

If I understand your question correctly this is how it goes.

freezeInC is set to 0.
freezeInF is set to get whatever fahrenheitFromCelsius will return.

So we jump to fahrenheitFromCelsius to see what is going on there.
fahrenheitFromCelsius is taking one argument with a type float. In this case we are passing freezeInC in the main function, and it was set to 0.

In the function fahrenheitFromCelsius(float cel), there is a line that reads:
float fahr = cel * 1.8 + 32.0;
so that float cel is still 0

C is a procedural language so instructions are executed step by step. Everything is executed in main() in order. So at first it sets a variable to 0, then it sees that another variable is set to some function, so it jumps to that function and executes it step by step until we return something, once we return something we can finally assign that value and continue on executing instructions line by line.

This is all oversimplification but I hope it gets the point across and helped you out.


#3

Can someone please explain what it means to “return” something? Does it have something to do with giving the information in the function to the main function? Also can we use return (“any expression”) or does it have to be specific to the variables you presented in the function. Thanks


#4

Functions are used to perform computations; computations can produce tangible results.

A function can pass the result of its computation back to its invoker. One common way to do this is to use a return statement:

Foo MakeFoo () {
   Foo foo = ProduceFoo ();
   return foo;   
}

The type of the expression used in the return statement must match the type of the return value in the function declaration.

In the example above, the type of the return value in the function declaration (Foo MakeFoo ()) is Foo, and the type of the expression in the return statement (return foo) is also Foo.

[Become a competent programmer faster than you can imagine: pretty-function.org]