What is the difference between data types Enum, struct and Union in C?

Asked

Viewed 3,911 times

4

I am reading the GNU’s C manual and I’m in the data types section and I notice a certain similarity between the types enum, struct, and union. Is the syntax the same, or is there something that differs between them? In which cases should I use which?

2 answers

4


Although they have similar syntaxes their functions are very different, the union is a chameleon structure, and an enumeration has constant data.

struct

A structure has a set of members, that is, each member listed there will be part of the structure, it is additive. Its size is the sum of the members plus the alignment.

union

A union has a single die among a variety available among its members, that is, only one member will be used in fact, excluding the possibility of others. Its size is that of the largest member, considering the alignment. It is productive (it is the product of the members).

From the example of the manual:

 union numbers {
     int i;
     float f;
 };

numbers is a union structure that or will have a whole die or will have a floating point dice. It depends on architecture, but probably both have the same size (4 bytes, in most cases), so it can be said that numbers will have 4 bytes (always use sizeof to discover).

The union is very useful to "chat" with the hardware since it can provide data of various types. This is a way to streamline the data. So you can have a single data that can take various forms (types), but several Apis use it to facilitate the passage of parameters or give flexibility.

It is also useful for creating a "variable type", similar to what dynamic languages usually have. Alias this is an internal technique that these languages use for their own variables. It is a form of polymorphism. It is common for the union to be within a structure with another member indicating which type is being guarded at that time, this is called tagged Union.

It has a technique that is used to mount or unlock a die. You can for example mount a struct with 4 members of the char (1 byte therefore) and then creates a union with 2 members, one is struct, and another is a int. So you can put each of the bytes in struct and then access the data by the member who is a int, it will be seen as a thing. If it is mounted in the right way, it will form a valid number. A more "correct example":

typedef union {
    struct {
        int8_t a;
        int8_t b;
        int8_t c;
        int8_t d;
    };
    int32_t x;
} meu_tipo;

meu_tipo var;
var.a = 0xFF;
var.b = 0xC0; 
var.c = 0xA5;
var.d = 0x0F;
int32_t y = var.x;

I put in the Github for future reference.

It is possible to do this even with bits instead of bytes.

enum

Enumeration is a way to use constant (compile-time-resolved) data that is related in a set. The behavior resembles the union a little. An object of this type will only have one value, the others are exclusionary. In it, instead of having any given, what is used is the member itself that has a fixed value defined in its own structure.

The data of each member is usually a numerical sequence and it is possible to do mathematical operations with them, but it is possible to give values you want for each member. If you leave the pattern the compiler considers a sequence starting from 0.

If there is no compiler extension the type of each member is always int and a value belonging to that enumeration can be used where a int can be used, given the weak C typing.

For many programmers this is the best way to use constants in C. Of course it depends on the goal.

There are those who like to use the names in uppercase as with the #define, but many programmers no longer do this because they do not have the same need of the past.

enum Direcao {Norte, Sul, Leste, Oeste}; //Norte é 0 e Oeste é 3
enum Permissao {Ler = 1, Escrever = 2, Apagar = 4, Executar = 8}
int p = Ler | Escrever; //vale 3 indicando que estas duas permissões estão ativas

I put in the Github for future reference.

  • I liked the example you made with Enum :) but I was giving a new read and it seems that Union only works with whole types proceeds? @bigown

  • 1

    The enum yes, the union definitely not.

  • In a better way with python’s Dict hehe

  • 1

    No, you can’t compare the two. Some people try, but it’s quite different. Of course you can use the dict Python to simulate an enumeration, but has several differences between them. The opposite is not true.

  • are different but I said it seems to access the values by indices

  • I think it was missing to mention that in C the Enum valroes are processed at compile time - the generated ojbeto code does not even know that there was an Enum - only see integer value.

  • (Except for debugging markings, of course)

  • @jsbueno is, I did not put here because I had answered this to him just before, I’ll see if I put here or do a link. Thank you.

Show 3 more comments

2

ENUM

It’s quite different from the rest, since it’s a list of numbers with easier names to use.

For example, you can create the list with the two types below:

typedef enum 
{
    TIPO_NM = 0,  //numero
    TIPO_ST       //string
}TIPO_VARIAVEL

Then, you can make a switch, for example, treating each of the Enum cases and dealing with the received types appropriately. The program will consider the number 0 for TIPO_NM and 1 for TIPO_ST, making it easier to read what each of the types means by one person. The more types you have, the more important it is to have an Enum.

STRUCT

It is the keyword for variable structures. Any set can be represented here.

For example, in the structure below a message is represented, imagining that all messages of a given communication always have 10 bytes of message body, a crc integer and a key long that identifies the message:

typedef struct
{
    char mensagem[10];
    int crc;
    long chave;
}Mensagem

UNION

It means that in the same structure, it can be used one way or another. This serves to save space and bytes are interpreted differently in each Union case.

For example, if the above struct is used as Union, it may be a number or string message depending on the long received. Then the interpretation would be different in each case, but the same structure would be fed whenever it received a new message.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.