What are the drawbacks of using enum ?

Share the Article

Although enum is a very handy way of working with integers, because it attaches human-readable (enumerated) names to list of numbers. The enums therefore, greatly improve the readability of code.

Example:

#include <iostream> using namespace std; int main() { enum validcolors { red, green, yellow }; for (int i=red; i<=yellow; i++) { cout<<"Hello - " << i << endl; } return 0; }

Output

Hello - 0 Hello - 1 Hello - 2

However, there are serious drawbacks with enum variables in standard C++.

First drawback

Drawback is that the enums by its basic nature pollute the scope where it is defined. This means that apart from being the enumerated name, the user will no longer be able to use this name any longer in same scope. Example, any of the variable in same scope cannot use this name.

enum validcolors { red, green, yellow }; int red = 8; // this line is problematic

Output

Result is Compiler Error: error: ‘int red’ redeclared as different kind of symbol

Please note, if the enum definition and variable definition would have been in different scope, then compiler will be ok.

Main Funda : Enum pollutes the scope

Second drawback

Another drawback with enums is that although from outside they look like names but in reality they are integers so they implicitly convert to any other data type which is compatible with integers. Like, an enum may get implicitly converted to floating-point types (float, double) or even to a different enum variable whose meaning is completely different.

Compiler sees the following code as absolutely ok !

enum validshapes { circle, rectangle, triangle }; int newcolor = red; newcolor = circle; // This is outrageous

Also, following code is ok too !

if( red < 2.3) { cout << “correct” }

Such coding practices will potentially leave loop-holes and will be prone to misuse.

Main Funda: Enums are just integers and they get converted implicitly like integers

The last drawback

Final drawback is that enums cannot be forward declared. The following code will not work.

enum validcolors; class shape { void draw(validcolors aColor); };

The result is an error:

error: ‘validcolors’ has not been declared

The definition part is so much important for compilers because, they need to assign proper integral types (like, std::uint8_t or std::uint16_t or std::uint32_t) to store an enum, and this can happen only after the complier see the whole definition. Generally, the compiler chooses best possible match to optimize on storage size and speed.

Main Funda: Enums cannot be forward declared because compiler do now the exact size of data type.

How modern C++ has solved this problem

C++11 resolves all the drawbacks of old style enums. Now, the enums have evolved into a new datatype called “scoped enums”. Now, they are no longer just a name of integer value but they are now more like a class.

The (scoped) enum is now similar to a class, therefore enum now follows proper class semantics. This means, the program should access the name with scope resolution operator (just like it does for accessing member of any class) The enum will simply cannot act like integers by default.

Just like, class members who never pollute the scope, in the same way enumerated names will not pollute the scope now.

enum class validcolors { red=1, green, yellow }; validcolors i=validcolors::red;

Scoped enum has to be explicitly cast to specific types to get the desired functionality (even for making it work like integers)


validcolors i=validcolors::red; cout << static_cast<int>(i); // Correct way cout << i ; //Incorrect way

The forward declaration will be completely valid for scoped enum (in C++11) because the enum is more like a class.

Main Funda: Scoped enums has solved the fundamental issues with enums.

Related Topics:

 What are the drawbacks of using enum ?
Which member functions are generated by compiler in class?
How to stop compiler from generating special member functions?
Compiler Generated Destructor is always non-virtual
How to make a class object un-copyable?
Why virtual functions should not be called in constructor & destructor ?
Explaining C++ casts
How pointer to class members are different ?
How std::forward( ) works?
What is reference collapsing?
How std::move() function works?
How delete keyword can be used to filter polymorphism
Rule of Three

Share the Article

4,177 thoughts on “What are the drawbacks of using enum ?

  1. Howdy! I could have sworn I’ve been to this website before but after browsing through many of the posts I realized it’s new to me. Regardless, I’m definitely pleased I came across it and I’ll be bookmarking it and checking back regularly.

  2. Having read this I thought it was rather enlightening. I appreciate you spending some time and effort to put this content together. I once again find myself spending a significant amount of time both reading and commenting. But so what, it was still worthwhile!

  3. Ethereum lança upgrade Berlin e prepara caminho pra deflação, ou seja, ao invés de continuar uma emissão eterna, a criptomoeda vai implementar um mecanismo de burn (queima). Outra grande mudança que está sendo preparada para o ETH 2.0 é a migração para o sistema Prova de Trabalho, acabando com a figura do minerador. Ethereum atinge capitalização de mercado de USD 320 bilhões, ultrapassando a Platina, além do banco chinês ICBC, e a gigante de pagamentos Paypal. – Agosto de 2021: A hard fork London apresenta taxas-base para cada transação e queima taxas de transação em vez de alocá-las a mineradores. Lembrar-me Existe um mecanismo chamado de bomba-relógio de dificuldade, que fica embutido na rede da Ethereum. É este mecanismo que torna a mineração dos tokens Ether cada vez mais difícil, e uma vez que atingirmos o limite desta bomba-relógio, o tempo gasto para minerar cada bloco será muito longo, implicando numa queda na lucratividade dos mineradores e em transações muito lentas. Os desenvolvedores da Ethereum querem garantir que os mineradores não tenham escolha a não ser interromper totalmente a mineração na Ethereum 1.0 e assim passarem a minerar a nova rede Ethereum 2.0, após a conclusão de seu lançamento. https://fair-wiki.win/index.php?title=Bitcoin_wallet_list This wallet starts from 99 USD. SO it is not suitable for a newbie investor with a small amount of money. Small investors are preferred to use the software wallets as they are free & easy to use. The device needs to be connected every time to the computer for accessing the wallet. There are many incidents of data breaching. All images, branding and wording is copyright of MetaMask. All content on this page is used for informational purposes only. CryptoSlate has no affiliation or relationship with the product mentioned on this page. The code is able to replace the address for many coins, such as Bitcoin, Ethereum, XMR, DOGE, etc. The first PowerShell script is responsible for executing AgentTesla, which is a .NET-based Remote Access Trojan with many capabilities, such as stealing browser’s passwords, capturing keystrokes, clipboard, etc.

  4. Hey there would you mind stating which blog platform you’re using? I’m planning to start my own blog soon but I’m having a hard time making a decision between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something completely unique. P.S Sorry for getting off-topic but I had to ask!

  5. Business etiquette is an agreed-upon list of rules for communication that help 샌즈카지노 create a healthy work environment; one that fosters respect for colleagues, vendors, and customers. A thorough understanding of business etiquette, and how to institute organizational changes, can help build trust among employees in your organization, as well as promote their professional growth.

  6. US online slots bonuses are an important part of choosing a place to play slots for real money. USA slots sign up bonuses is usually the highest promotion at casinos. There are hundreds of American online slots for USA casinos offer bonuses that sound great but the most important thing for a player is to find a trusted, and reputable casinos to play games. In this online gambling guide, we will discuss the following: Have you been taking advantage of the Uptown Aces Crazy Days USA slots sign up bonuses? Every day Uptown Aces have a different promotion. They are also offering a high $100 no deposit bonus for new customers. Try real money games free when you sign up for Uptown Aces using a link or a banner on this review page. – no casino bonusesReal money prosReal Money Cons– an opportunity to win real money https://opensourcebridge.science/wiki/Bitcoin_games_slots The agreement to plead guilty comes months after Seals with Clubs abruptly closed in February, an act closely followed by the raid by the Nevada Gaming Commission. Daniel Negreanu’s results and his always friendly and chatty demeanor at the tables did not go unnoticed by those who matter. In 2007, online poker giant PokerStars signed him as one of their Team Pro members and it wasn’t long before Kid Poker would become the main ambassador for the site. On Tuesday, Lewis released a new audio edition of “Liar’s Poker,” narrated by himself, as well as a five-episode companion podcast “Other People’s Money.” I talked to Lewis about how Wall Street has — and hasn’t— changed since the original release of the book and why in some ways it’s even worse today.

  7. Hello, Neаt post. There’s a problem with үour website in іnternet explοrer,
    would test thiѕ? IE still is the marketplace leader and a huge part of other
    peoplе ᴡill leave out your fantastic writing becauѕe of this problem.