Functions that return a struct
From Applied Science
- Function that returns both roots of a second degree polynomial equation:
/* Struct to store two values */ struct roots { float x1, x2; }; /* Function that receives the coefficients a, b and c and returns the roots of the second degree polynomial (it doesn't cover the case of a negative delta) */ struct roots Quadratic (int a, int b, int c) { struct roots x; float delta; delta = b*b - 4*a*c; x.x1 = (-b + sqrt(delta))/(2*a); x.x2 = (-b - sqrt(delta))/(2*a); return x; }
Functions can also be of 'struct' type and return a 'struct', much like a function that returns an integer or a float. Inside the function "Quadratic" we have to declare a variable of the same struct type to store both roots.
The syntax of 'roots' includes curly brackets, but it's a struct, not a function. That's why it ends with a semi-colon.
Note: the function is not returning two variables. It's returning the values stored in the struct "x", which type's "roots".
- Calling the above function:
/* 1st way */ printf("%f, %f", Quadratic(1, 2, -3).x1, Quadratic(1, 2, -3).x2); /* 2nd way*/ struct roots x; x = Quadratic(1, 2, -3); printf("%f, %f", x.x1, x.x2);
Both should produce the same result: print the roots -3 and 1.