Concept
How can pass-by-reference parameters return both roots of a quadratic equation?
ComputerScienceOne / Quadratic Roots
"Another advantage of passing variables by reference is that we can “return” multiple values with one function call. Functions are limited in that they can only return at most one value. But if we pass multiple parameters by reference, the function can manipulate the contents of them, thereby communicating (though not strictly returning) multiple values. Consider again the problem of computing the roots of a quadratic equation, ax^2 + bx + c = 0, using the quadratic formula, (-b ± √(b^2 - 4ac)) / 2a. Since there are two roots, we may have to write two functions, one for the “plus” root and one for the “minus” root, both of which take the coefficients, a, b, c, as arguments. However, if we wrote a single function that took the coefficients as parameters by value as well as two other parameters by reference, we could compute both root values and place each one in two pass-by-reference variables.\n\nvoid quadraticRoots(double a, double b, double c,\n\ndouble *root1, double *root2) {\n\ndouble discriminant = sqrt(b*b - 4*a*c);\n\n*root1 = (-b + discriminant) / (2*a);\n\n*root2 = (-b - discriminant) / (2*a);\n\nreturn;\n\n}\n\nBy using pass-by-reference variables, we avoid multiple functions."
Related Ideas
- How can PHP pass variables by reference to return multiple quadratic roots?ComputerScienceOne · Quadratic Roots
- How can a quadratic roots function return error codes?ComputerScienceOne · Error Handling By Design
- How can pointers be used to pass variables by reference?ComputerScienceOne · Passing By Reference
- How do pointers pass values by reference in C?ComputerScienceOne · Function Pointers
- How can a C program compute the roots of a quadratic equation?ComputerScienceOne · Computing Quadratic Roots
- How do you invoke functions that accept pointer parameters?ComputerScienceOne · Passing By Reference
- How can conditionals handle invalid inputs and special cases in a quadratic roots program?ComputerScienceOne · Quadratic Roots Revisited
- How does PHP compute the roots of a quadratic equation?ComputerScienceOne · Computing Quadratic Roots