Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between struct and enum?

Tags:

I am newbie to C++, and want to understand what is the difference between saying

typedef enum stateUpdateReasonCode {     a=1,     b=2,     c=3 } StateUpdateReasonCode; 

and

struct StateUpdateReasonCode {    a=1,    b=2,    c=3 }; 

What is difference between them ? Wy would we use one over another ?

Kind Regards

like image 379
AndroidDev Avatar asked Dec 19 '13 11:12

AndroidDev


1 Answers

An enum and a struct are totally different concepts, fulfilling different purposes.

An enum lets you declare a series of identifiers for use in your code. The compiler replaces them with numbers for you. It's often useful for making your code more readable and maintainable, because you can use descriptive names without the performance penalty of string comparisons. It can also make the code less bug-prone because you don't have to keep writing in specific numbers everywhere, which could go wrong if a number changes.

A struct is a data structure. At its simplest, it contains zero or more pieces of data (variables or objects), grouped together so they can be stored, processed, or passed as a single unit. You can usually have multiple copies (or instances) of it. A struct can be a lot more complex though. It's actually exactly the same as a class, except that members are public by default instead of private. Like a class, a struct can have member functions and template parameters and so on.

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.

From a coding standpoint, each identifier in an enum doesn't have its own type. Every member within a struct must have a type.

like image 74
Peter Bloomfield Avatar answered Oct 03 '22 05:10

Peter Bloomfield