DEV Community

Discussion on: Did I learn it? #1

Collapse
 
moshikoi profile image
MoshiKoi

Your code looks mostly fine; though usually you would ALLCAPS unscoped enumerations by convention.
However, unscoped enumerations have pretty much been superceded by scoped enumerations. For instance:

enum class Color { Red, Green, Blue };
Enter fullscreen mode Exit fullscreen mode

This is due to scoping and strong typing. Unscoped enumerations are unscoped, meaning you end polluting the namespace. (This is also why using namespace std; is also not recommended.) In addition, they are implicitly convertable to their underlying type, which can hide bugs.1 Take for instance your above code, but without the operator overload.

#include <iostream>

enum Color
{
    black,
    red,
    blue,
};

int main()
{
    Color shirt{ blue };
    std::cout << "Your shirt is " << shirt; // prints "Your shirt is 2"

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

This is probably not what you want. With a scoped enumeration, the equivelant code would cause a compilation error.

#include <iostream>

enum class Color
{
    black,
    red,
    blue,
};

int main()
{
    Color shirt = Color::blue;
    std::cout << "Your shirt is " << shirt; // error: invalid operands to binary expression ('basic_ostream<char, char_traits<char>>' and 'Color')

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

As an aside, did you know you can enable syntax highlighting by putting the language name after the three backticks?

```c++
// your code here
```
Enter fullscreen mode Exit fullscreen mode

  1. This is sometimes useful, however] 

Collapse
 
dhducky profile image
DHDucky

I've just started coding and just found this interesting to start covering about. Next week there should be one on either scoped enumeration (or struct) so I'll get to learn about what you're talking about. And the thing about the syntax highlighting is much appreciated as this is my first blog/post ever on any type of social media. Have a nice day!