Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why package a single enum in a struct?

Tags:

c++

c

enums

struct

This is written by someone who has left the company. I can't see any reason to do this and am curious if there's something I am missing.

enum thing_type_e
{
   OPTION_A = 0,
   OPTION_B,
   OPTION_C,
   OPTION_D
};

struct thing_type_data_s
{
   enum_type_e mVariable;
};

I supposed it's possible he was going to add more to the structure, but after looking at how it is used, I don't think so.

Barring "he was going to add more to the structure," why package a single enum in a struct? Is there some motivation I'm not thinking of?

Update:

As asked in the comments, he used it in this fashion:

void process_thing_type(thing_type_data_s* ParamVariable)
{
    local_variable = ParamVariable->mVariable;
    ...
}

This was originally built with GCC 3.3.5 if it makes any difference.

like image 803
kmort Avatar asked Jan 23 '14 20:01

kmort


People also ask

Can a struct contain an enum?

The enum constants are also known as enumerators. Enum in C# can be declared within or outside class and structs. Enum constants has default values which starts from 0 and incremented to one by one.

What is a packed enum?

4.11 The __packed__ Attribute When attached to an enum definition, it indicates that the smallest integral type should be used. Specifying this attribute for struct and union types is equivalent to specifying the packed attribute on each of the structure or union members.

When would you use a struct vs an enum?

One of the vital difference between structs and enums is that an enum doesn't exist at run-time. It's only for your benefit when you're read/writing the code. However, instances of structs (and classes) certainly can exist in memory at runtime.

What is the purpose of using enumeration?

Enumerations make for clearer and more readable code, particularly when meaningful names are used. The benefits of using enumerations include: Reduces errors caused by transposing or mistyping numbers. Makes it easy to change values in the future.


1 Answers

Possibly to enforce some type safety. Old-style enums are implicitly convertible to integral types, and this is not always desirable. Besides this, they are unscoped.

C++11 adds scoped enumerations (or "class" enums) to fix both of these issues.

Here's an example:

void foo(int) {}

int main()
{
  foo(OPTION_A);  // OK
  thing_type_data_s s = { OPTION_A };
  foo(s);  // Error
}
like image 153
juanchopanza Avatar answered Sep 27 '22 17:09

juanchopanza