Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of enums?

Tags:

c++

c#

What is the point of an enum being used for something like a switch statement when you then have to cast them to ints?

Isn't it just better to use a few const ints? I want to use enums but the cast makes them seem clunky. I thought they were meant to be ints but they're something else?

Do they have the same behaviour in C++?

sorry for the badly worded question, my brain is fried.

like image 292
Dollarslice Avatar asked Nov 04 '11 14:11

Dollarslice


People also ask

What is the point of enums in C?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.

Why enums should not be used?

Enums are good to represent static/singleton objects but should never be used as value objects or have attributes that get set during usage. You can use an enum to 'type/label' a two week duration, but the actual start/end dates should be attributes of a class DateRange.

What is the point of enums in Python?

Python enums are useful to represent data that represent a finite set of states such as days of the week, months of the year, etc. They were added to Python 3.4 via PEP 435. However, it is available all the way back to 2.4 via pypy. As such, you can expect them to be a staple as you explore Python programming.

Why enums are better than strings?

They are type safe and comparing them is faster than comparing Strings.


2 Answers

The entire point of enums are to make your code more readable. They are not casted to ints, since they are by default ints. The only difference is instead of going back and forth checking what int values you may have, you can have a clear set of enums to make the code more readable.

like image 56
onit Avatar answered Sep 29 '22 22:09

onit


Enumerations have semantic value that helps your code be easier to read. They are a bit more useful than just using constant values themselves since you can group them together.

Think of an enum as a way of namespacing a group of related constant values.

like image 42
Andrew Hare Avatar answered Sep 29 '22 20:09

Andrew Hare