Skip to study material
← Question index

QUESTION 12

Explain functions that return structure values.

5 marks

Answer in brief

Returning a structure lets a function produce several related result members as one value.

Example interface

struct Pair { int minimum, maximum; };
struct Pair extremes(int a, int b);

Working

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.

Example trace

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.

Value versus address

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.

Advantages and cost

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.

Complete C example

main.c

Download main.c
/* 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;
}

Sample input and output

The example uses values in the code.

Output

Minimum = 4, maximum = 9