Step 4
Functions
Package a calculation as a function with typed parameters, and return its result.
Name a piece of work
A function packages a calculation under a name, so you can run it again with different inputs. You've already written one: main. Here's another:
double area(double width, double height) {
return width * height;
}
int main() {
std::cout << area(2, 3) << "\n"; // 6
std::cout << area(0.5, 4) << "\n"; // 2
}
- The first
doubleis the return type: the type of value the function gives back. - Then come its name and its parameters in parentheses, each with its own type.
- The body goes between the braces.
returnhands a value back to whoever called the function:area(2, 3)runs the body withwidth = 2andheight = 3, and the whole call becomes6.
Defining a function doesn't run it; calling it does. A function must be defined (or at least declared) above the code that calls it, so helper functions go above main.
A function that gives nothing back has the return type void:
void report(double x) {
std::cout << "x = " << x << "\n";
}
return versus printing
Printing shows a value to you. return gives it back to the program, which can store it or use it in more maths: double total = area(2, 3) + area(1, 1);. The grader calls your functions and checks what they return, so always return the answer.
Every robot lesson is built this way: you'll write functions like forward_kinematics(q) that turn joint angles into a position.
Your task
- Write
deg_to_rad(deg)so it returnsdegconverted to radians. - Write
reach(l1, l2)so it returns the reach of a two-link arm: the two lengths added together.
main calls both so you can see what they return. The grader tries each one on several inputs.