As we have already mentioned, The type of the expression in the return statement must match the return type of the function itself. When you declare that the return type is double, you are making a promise that this function will eventually produce a double value. If you try to return with no expression, or return an expression with the wrong type, the compiler will give an error.
Although it is possible to return a literal value with something like return 42;, it is much more common to want to return the result of a computation. We can either do so by returning an expression:
Much like when we pass a variable to a function, when we return a variable, the value of the variable is copied as it is returned. So although we might say of the function above βit returns areaβ, it is more accurate to say βit returns the value stored in areaβ .
The two approaches will produce the same result, but the second is often easier to read and debug. Especially when you are stepping through code, first calculating an answer and storing it into a variable, then returning the value of that variable, makes it easier to see what is going on.
Trying to βoptimizeβ code by using fewer local variables is almost always pointless. Focus on code that is easy to read and debug. The compiler can generally be counted on to turn your code into an efficient machine representation. There are times when programmers will write code in a specific way to optimize its speed, but you should not try to βoptimizeβ your use of local variables.
Every function must specify a return type in its prototype. But not every function needs to return a value. Some functions are used for their side effects - they do something, but they donβt produce a value. A function might print something to the screen, or play a sound or send a message over the network.
Because void functions do not return anything, there is no need to try to store their result. In fact, any attempt to use their result would be an error. If we wrote double result = printAsMoney(12.432345);, we are essentially saying double result = ; because printAsMoney(12.432345) evaluates to nothing.