From 940f2c971af4a1edb7ca6f2e8b46f008c366a451 Mon Sep 17 00:00:00 2001 From: Dmitry Kokorin Date: Mon, 29 Feb 2016 14:37:07 +0300 Subject: [PATCH] food_chain: X macro --- cpp/food-chain/food_chain.cpp | 48 ++++++++++++++++++++++------------- 1 file changed, 31 insertions(+), 17 deletions(-) diff --git a/cpp/food-chain/food_chain.cpp b/cpp/food-chain/food_chain.cpp index 9934c81..dabbf8f 100644 --- a/cpp/food-chain/food_chain.cpp +++ b/cpp/food-chain/food_chain.cpp @@ -6,9 +6,28 @@ namespace food_chain { using namespace std; +#define ANIMAL_TABLE \ +X(Fly, "fly") \ +X(Spider, "spider") \ +X(Bird, "bird") \ +X(Cat, "cat") \ +X(Dog, "dog") \ +X(Goat, "goat") \ +X(Cow, "cow") \ +X(Horse, "horse") + +#define X(a, b) a, +enum Animal { + ANIMAL_TABLE +}; +#undef X + +#define X(a, b) b, +static const char *animal_name[] = { + ANIMAL_TABLE +}; +#undef X -static const char *animals[] = - {"fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"}; static const char *verse_phrase[] = { "", @@ -21,8 +40,6 @@ static const char *verse_phrase[] = { "She's dead, of course!\n" }; -static const int size_of_animals = sizeof(animals) / sizeof(*animals); - string verse(int index) { @@ -31,27 +48,24 @@ string verse(int index) --index; result += string("I know an old lady who swallowed a ") - + animals[index] + + animal_name[index] + ".\n" + verse_phrase[index]; - if (index != size_of_animals - 1) { + if (index != Animal::Horse) { for (int i = index; i > 0; --i) { - if (i == 2) { + result += string("She swallowed the ") + + animal_name[i] + + " to catch the " + + animal_name[i-1]; - result += "She swallowed the bird to catch the spider " - "that wriggled and jiggled and tickled inside her.\n"; - } - else { + if (i == Animal::Bird) + result += string(" that wriggled and jiggled and " + "tickled inside her"); - result += string("She swallowed the ") - + animals[i] - + " to catch the " - + animals[i-1] - + ".\n"; - } + result += string(".\n"); } result += "I don't know why she swallowed the fly. "