1

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.

  • 1
    it's the same as declaring a variable as the result of the function instead of a hard-coded literal. – dandavis Jul 21 '20 at 20:28
4

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.

  • To add to And the Serial.println() function will be handed the value 7 for printing. Especially, it will be handed an int value of 7, which will eventually produce a different output than other data types. – DataFiddler Jul 22 '20 at 11:17
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.