計算機科学のブログ

ほしい物リスト

C - 構造体、共用体、ビットフィールド - 独自の構造を使う - enum

Head First C ―頭とからだで覚えるCの基本David Griffiths(著)、 Dawn Griffiths(著)、 中田 秀基(監修)、 木下 哲也(翻訳)、 O’Reilly Media)の5章(構造体、共用体、ビットフィールド - 独自の構造を使う - 分割して構築する)、p.256(コードマグネット)の解答を求めてみる。

Makefile

all: main.c
	cc main.c && ./a.out

コード

main.c

#include <stdio.h>
typedef enum
{
    COUNT,
    POUNDS,
    PINTS
} unit_of_measure;

typedef union
{
    short count;
    float weight;
    float volume;
} quantity;

typedef struct
{
    const char *name;
    const char *country;
    quantity amount;
    unit_of_measure units;
} fruit_order;

void display(fruit_order order)
{
    switch (order.units)
    {
    case COUNT:
        printf("%i個の%sです。\n",
               order.amount.count, order.name);
        break;
    case POUNDS:
        printf("%2.2fポンドの%sです。\n",
               order.amount.weight, order.name);
        break;
    case PINTS:
        printf("%2.2fパイントの%sです。\n",
               order.amount.volume, order.name);
        break;
    default:
        break;
    }
}

int main()
{
    fruit_order apples = {"リンゴ", "イギリス", .amount.count = 144, COUNT};
    fruit_order strawberries = {"いちご", "スペイン", .amount.weight = 17.6, POUNDS};
    fruit_order oj = {"オレンジジュース", "アメリカ", .amount.volume = 10.5, PINTS};
    fruit_order orders[] = {apples, strawberries, oj};
    for (size_t i = 0; i < 3; i++)
    {
        display(orders[i]);
    }
}

入出力結果(Terminal, Zsh)

% make
cc main.c && ./a.out
144個のリンゴです。
17.60ポンドのいちごです。
10.50パイントのオレンジジュースです。
%