According to the understanding of beginners, the task of return is to return the corresponding parameter, which is further processed in the outer function.
In fact, the usage of return is not limited to this.
Returning parameter values from the called function
This type of application is the most common, usually in a function with a return value, returning a parameter value. This returned parameter can be a number or an expression. Generally, the return value is a single value, but if you want to return multiple values, you can refer to the following three points:
-
Set global variables. A global variable is a variable defined outside of any function, and it does not belong to any specific function. Therefore, although a value is returned in the calling function, the remaining return values can be assigned to global variables, achieving the effect of returning multiple values.
-
Use an array name or pointer as a function parameter, which returns an address. The main function can find multiple data to be returned based on this address.
-
Use a structure as a function parameter. A structure can contain various types of variables, and using a structure as a parameter is equivalent to packaging all return values together and returning them at once.
Ending a function early
Since return has the effect of transferring the program flow from the called function to the calling function, it is also used to terminate the function call. In other words, return is the only way to end a function early. When a function encounters return, it immediately returns, and the code after return is not executed. Therefore, a function can have multiple return statements, but only one will be executed. Return can be followed by a parameter as a return value, or it can be used without a parameter, simply indicating the end of the function.
Returning a function
If what follows return is a function, it means that the current calling function is exited, and after exiting, the function following return is executed, and then the program continues in the main function. Sometimes, return is used to return an operation, for example, when an error occurs during program debugging, it is necessary to return to exit the error function and print the reason for the error to the serial port. In this case, the function following return is used to print the error reason to the serial port.