Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Enum allocate Memory on C?

I'm trying to work with C and Assembly (intelx8086) language.

I'm also using one class that was implemented by a friend of mine. It has a

typedef enum data_10 {a=0,b=7,c=10,} data_10_type;

I want to work with this class bitwise (AKA construct it/destroy it on Assembly). My question is, how much memory does "enum" take?

like image 599
NacOverflow Avatar asked Sep 04 '12 15:09

NacOverflow


People also ask

How is enum stored in memory in C?

As enum types are handled as integral types, they are stored in the stack and registers as their respective data types: a standard enum is usually implemented as an int32; this means that the compiler will handle your enum as a synonym of int32 (for the sake of simplicity, I left out several details).

Does enum occupy memory?

An enum does not really take any memory at all; it's understood by the compiler and the right numbers get used during compilation. It's an int, whose size is dependent on your system.

What does enum do 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.

Where is enum stored?

A standard enum is usually implemented as an int32, the compiler will handle your enum as a synonym of int32 . Once a list of values is created for a enumeration those values are stored as literals against their display name(access name given at the time of declaration of enum).


2 Answers

Although it may vary from compiler to compiler, enum typically takes the same size as an int. To be sure, though, you can always use sizeof( data_10_type );

like image 77
Greyson Avatar answered Oct 15 '22 13:10

Greyson


Why don't you print it?

/* C99 */
#include <stdio.h>

typedef enum { a = 0, b = 7, c = 10 } data_10_type;
printf("%zu\n", sizeof(data_10_type));

The identifiers in an enumerator list are declared as constants that have type int (C11 §6.7.2.2 Enumeration specifiers), so sizeof(data_10_type) is often equal to sizeof(int), but it isn't necessary!

BTW, if you want to have a size in bits, just use the CHAR_BIT constant (defined in <limits.h>), which indicates how many bits there are in a single byte).

/* C99 */
#include <limits.h>
#include <stdio.h>

typedef enum { a = 0, b = 7, c = 10 } data_10_type;
printf("%zu\n", sizeof(data_10_type) * CHAR_BIT);
like image 29
md5 Avatar answered Oct 15 '22 12:10

md5