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 pass-by-reference parameters return both roots of a quadratic equation? | ComputerScienceOne | Bifalgorithm | Bifalgorithm