100DaysOfGameDev: Day 4

C++ is so ugly and beautiful once in a while, usually, it's just ugly. Today's topic included union type, enumerations, statments, condition statements, and loops. To start off union is disgusting. I understand why it can save some memory, but the amount of complexity it adds to the code is insane, not to mention most of the users do not use it properly anyway. In modern apps, if you have a union it means the poor design of a program since there are many other ways to organize the system and we have plenty of memory on top. Speaking of beauty and ugly, I wanted to talk about enums. Specifically enum class, which differentiates between Trafic_light::RED and Warning::RED as different REDs. Of course, there are plenty of ways to hack it, convert it to integers, and cast it back into a wrong range resulting in hard-to-find bugs. But it also allows me to write more expressive code, which I couldn't dream of doing in Java, specifically this code example which I can already see how I would use in games.

enum class Printer_flags {
    acknowledge=1,
    paper_empty=2,
    busy=4,
    out_of_black=8,
    out_of_color=16,
};

constexpr Printer_flags operator|(Printer_flags a, Printer_flags b)
{
    return static_cast<Printer_flags>(static_cast<int>(a) | static_cast<int>(b));
}

constexpr Printer_flags operator&(Printer_flags a, Printer_flags b)
{
    return static_cast<Printer_flags>(static_cast<int>(a) & static_cast<int>(b));
}

void f(Printer_flags p)
{
    // if printer is out of ink, then scream
    if (p & (Printer_flags::out_of_black|Printer_flags::out_of_color))
    {
        std::cout << "SCREAM\n";
    }
}

Note, while testing the code, I noticed several issues as to why the code wouldn't compile. First, in the original code example ( page 220 overloading operators |, & ), they had extra parenthesis. Furthermore, since the enum class cannot be implicitly converted to bool, the following statement will fail p & (Printer_flags::out_of_black|Printer_flags::out_of_color). Going forward to condition statements, they had a typo in a comment ( page 225 ). Seems like since these are relatively simple topics of the book, they haven't been proofread properly, which sucks.