Returning a Structure

A function can also return a structure. return gives back only one value, but that one value can have several members. In the lesson on pointers, a function gave back two results through two pointer parameters. With a structure, it's often simpler: put the results into one structure and return it. This function turns a number of seconds into minutes and seconds:

#include <stdio.h>

typedef struct {
    int minutes;
    int seconds;
} Time;

Time from_seconds(int total) {
    Time result;
    result.minutes = total / 60;
    result.seconds = total % 60;
    return result;
}

int main(void) {
    Time run = from_seconds(1000);
    printf("%d min %d s\n", run.minutes, run.seconds);
    return 0;
}

This prints:

16 min 40 s

The return type in front of the function's name is Time. The function creates a local variable result, fills in its members and returns it. As with parameters, the structure is copied: run in main gets a copy of result, and result itself disappears when the function ends, like any local variable. You could also create result with its values right away: Time result = {total / 60, total % 60};.

A function can also return one of the structures from an array it gets. return items[i]; returns a copy of that element. Assigning works the same way: best = items[i]; copies the whole structure into the variable best, all its members at once. That's how you will find the cheapest product in the task below: remember the first product, and whenever a cheaper one comes along, remember that one instead.

Instructions

Above main, write a function Product cheapest(const Product items[], int count) that returns the cheapest product in the array.

Below the loop in main, call the function and store what it returns: Product best = cheapest(shelf, 4);. Then print Cheapest: Yogurt (14.90), with the name and the price taken from best.

Write one more function, Product with_discount(Product item, int percent), that returns the product with its price lowered by percent percent. It gets a copy, so it can change the copy's price and return it; the original stays as it was. (Watch out: percent / 100 is a whole-number division.) At the end of main, call it with best and 10, and print the old and the new price: Yogurt: 14.90 -> 13.41.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

8/9