2 Replies - 427 Views - Last Post: 04 October 2019 - 09:28 AM Rate Topic: -----

#1 albert003   User is offline

  • D.I.C Addict

Reputation: 37
  • View blog
  • Posts: 780
  • Joined: 15-December 14

Can't find a use for enums

Posted 04 October 2019 - 08:51 AM

I was going over a program sample a mentor gave me which had an enum and I went through to various websites online as well as video tutorials and I honestly can't see a need or reason for using it. To me, it seems like using a switch function (My text book says its cleaner, but to me its cleaner using if statements). Could anyone give me a real life example where they have used enums?

Most of the examples I've found are similar to this.
enum{
    red,
    white,
    blue

};
int main()
{
    std::cout << red << std::endl;
}



Is This A Good Question/Topic? 0
  • +

Replies To: Can't find a use for enums

#2 sepp2k   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2754
  • View blog
  • Posts: 4,414
  • Joined: 21-June 11

Re: Can't find a use for enums

Posted 04 October 2019 - 09:15 AM

View Postalbert003, on 04 October 2019 - 05:51 PM, said:

I honestly can't see a need or reason for using it.


What would you use instead? Hard-coded integers (setColor(0) instead of setColor(red))? Manually defined global constant int variables (const int RED = 0; or #define RED 0 and then setColor(RED))? Strings (setColor("red"))?

Each of those have their own downsides, so if you tell us which one of those you'd pick over enums, we can discuss that approach's up- and downsides over enums.


Quote

Could anyone give me a real life example where they have used enums?


  • As the tag in tagged unions, for example when implementing ASTs in C.
  • To represent the current state in state machines.
  • To represent a card's rank and suit in a card game.

Was This Post Helpful? 2
  • +
  • -

#3 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 15302
  • View blog
  • Posts: 61,369
  • Joined: 12-June 08

Re: Can't find a use for enums

Posted 04 October 2019 - 09:28 AM

It's super nice for readability and database storage as well.

The readability part because words are linked to discrete values. I may have a list of 50 types which I could put into an enum and get that value translation without having to scroll around for it.

The db part because when I want to store the data into a db it stores as a number.


#include<iostream>
using namespace std;
enum MyType
{
	TRANSPORTATION = 0,
	SECURITY = 1,
	COMMUNICATION = 2
};


int main()
{
	MyType foo = TRANSPORTATION;
	cout << foo << endl;

	if (foo == 0)
	{
		cout << "toot toot " << endl;
	}


	foo = SECURITY;
	cout << foo << endl;

	if (foo == SECURITY)
	{
		cout << "run it's the fuzz!" << endl;
	}

	return 0;
}



0
toot toot
1
run it's the fuzz!

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1