Define an enum (or enum class, if using a C++11 capable compiler) named Animal that contains the following animals: pig, chicken, goat, cat, dog, ostrich. Write a function named getAnimalName() that takes an Animal parameter and uses a switch statement to return the name for that animal as a std::string. Write another function named printNumberOfLegs() that uses a switch statement to print the number of legs each animal walks on. Make sure both functions have a default case that prints an error message.
//POST 1 / 2
//I'll do this for ya, but it's important to know what you're doing instead of just cheating. Feel free to ask if you have any questions on how they work and I'll do what I can to help, mkay?
//enums just make lists of named constant integers
//The first entry always starts at 0, with each entry afterwards being 1 higher than the previous.
pig, chicken, goat, cat, dog, ostrich
//pig = 0, chicken = 1, goat = 2, etc.
//You can also assign them their own values, with the one after being continuing from the assigned value. If we set chicken to 7, for example
//pig, chicken = 7, goat, cat, dog, ostrich
//They would become 0, 7, 8, 9, 10, and 11 respectively.
//Personal gripe, I hate lower case first names. It's such a java thing and it looks absolutely awful. Eh, c'est la vie.
std::string getAnimalName(Animal animal)
//switches are just a more compact version of an if-then-else tree.
//"cases" are for each of the ifs, with "default" being the final else.
case pig: return "pig";
case chicken: return "chicken";
case goat: return "goat";
case cat: return "cat";
case dog: return "dog";
case ostrich: return "ostrich";
default: return "[Error] Unknown Animal";
//Notice that we don't need a return here because all possible control paths are handled in the switch statement above.
//Continued in next post...
//POST 2 / 2
void printNumberOfLegs(Animal animal)
//An interesting property of switch statements is that they 'fall through' to the next case until it hits a break or return statement. For example:
//Notice how there's no break or return until after cout here. Both chicken and ostrich will perform this same bit of code.
std::cout << getAnimalName(animal) << " has 2 legs\n";
//Same goes for here. pig, goat, cat, and dog will all print 4 legs.
std::cout << getAnimalName(animal) << " has 4 legs\n";
std::cout << "[Error] Unknown Animal\n";
printNumberOfLegs((Animal)47); //Invalid animal, should print the error case.
//Hopefully this helps. You should be able to just toss this into a .cpp file, compile it, and run.
//Maybe as an exercise, try adding a new kind of animal. A spider would be a good example, add Charlotte to your farm. :)