Arduino Asked by Grant Scott on November 13, 2021
something I’ve never understood and still don’t is, what does the return type do specifically? Everyone in tutorials just say that void returns nothing and int returns int, etc. But what does that mean? Where is it returning to? I can’t seem to understand what everyone’s talking about when they discuss functions.
The reason is that a function is evaluated just as any other expression would be. Every expression - `(x**x - 3*x + 5), for instance - has a value and a type (unless the type is void, then it has no value, or not a defined one), and that includes functions. The compiler needs to know the type of every element of the expression in order to know how to use that element in an operation (arithmetic or other kinds). Sometimes a value has to be converted from one type to another to combined with another element or assign to a variable, and knowing the type of each element is the only the compiler knows how to accomplish this.
Here is an example:
float squareroot(float x);
could declare a function that takes a floating point number and returns its square root as a floating point number. If you assign that value to an integral of variable, the compiler needs to see that the functions does not return an integer but a float, so it includes the appropriate code to convert the float to an integer (by truncating the fractional part, in this case).
If the function could be written without declaring its return value type, the compiler would be unable to make the conversion, or even to know whether one will be needed.
Answered by JRobert on November 13, 2021
It returns it to whatever the function is being assigned to.
Take the function:
int plus(int a, int b) {
return a + b;
}
That function takes two integers, adds them together, and "returns" them as an integer.
You can then do:
int c = plus(3, 4);
and c
will be handed the value 7
by the function.
Equally you can do:
Serial.println(plus(3, 4));
And the Serial.println()
function will be handed the value 7
for printing.
The type of the return defines the kind of data that can be returned.
Oh, and void
doesn't mean "returns nothing", but means "doesn't return anything" - which means you can't assign it to anything since there's nothing returned to assign.
Answered by Majenko on November 13, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP