Jakey
Jakey

Reputation: 160

What does a bitwise shift in a C enum definition do?

I'm new to C and wanted to know, what does a bitwise shift 1 << 9 in an enum definition do in this case below:

static enum {
    DEAD, LIVE
} state[1 << 9];

Upvotes: 1

Views: 118

Answers (2)

chqrlie
chqrlie

Reputation: 144695

The code defines a static array of values of an unnamed enum with 2 values DEAD (0) or LIVE (1). The number of elements for this array is specified as 1 << 9 (512).

It would be more readable to separate these as

enum status { DEAD, LIVE };
static enum status state[1 << 9];

Note also that the size of this enum type is implementation specific. If compactness is an issue, you should use an array of unsigned char, or use a bitwise representation but you would need to hand code it as the C language does not have built-in support for arrays of bits:

enum { DEAD = 0, LIVE = 1 };
static unsigned char state[1 << 9];

Upvotes: 4

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

The expression 1<<9 is the same as 29, which is 512.

So an array of 512 enums is declared.

Upvotes: 6

Related Questions