QUESTION 11
Can a C function return a structure?
2 marksAnswer
Yes. Its declared return type can be a complete structure type, and return can supply a compatible structure value.
QUESTION 11
Yes. Its declared return type can be a complete structure type, and return can supply a compatible structure value.
QUESTION 12
Returning a structure lets a function produce several related result members as one value.
struct Pair { int minimum, maximum; };
struct Pair extremes(int a, int b);The function creates a local result object, fills its two members and returns its value. The caller can initialise or assign a compatible structure object from that returned value. The caller does not need to receive a pointer to the function’s ordinary local object.
extremes(9, 4) sets minimum to 4 and maximum to 9. The returned Pair initialises result in main. Reading result.minimum and result.maximum displays both outputs. The local function object can finish its lifetime because its value has been returned.
Returning a local structure value is valid. Returning the address of an ordinary automatic local structure is different and unsafe for later access, because that object’s lifetime ends. If the returned record contains pointers, their targets must separately remain valid; value return does not extend those targets’ lifetimes.
A result record gives meaningful names to related outputs and avoids several unrelated output parameters. It is useful for a minimum/maximum pair, a coordinate or a parsed record. For the fixed two-int result, the example uses O(1) work and extra space. Larger record copying and pointer-target processing depend on their sizes and the implementation.
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
struct Pair { int minimum, maximum; };
struct Pair extremes(int a, int b)
{
struct Pair result;
result.minimum = a < b ? a : b;
result.maximum = a > b ? a : b;
return result;
}
int main(void)
{
struct Pair result = extremes(9, 4);
printf("Minimum = %d, maximum = %d\n", result.minimum, result.maximum);
return 0;
}The example uses values in the code.
Minimum = 4, maximum = 9