iliyaitsme
iliyaitsme

Reputation: 71

Enum iteration in C

I'm programming in C and I have some kind of enum, lets say there's an enum name hello and it has 3 properties inside of it- A, B and C.

How can I make A equal 0, B equal 2, and C equal 3, rather than each value simply incrementing by one?

Thanks in advance!

Upvotes: 2

Views: 123

Answers (3)

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4041

You can try this.

enum X
{
  A = 0,
  B = A + 2,
  C = B + 1
};

Or else you can leave that without assigning

enum X
{
  A,
  B = A + 2,
  C
};

While giving the A is automatically assign the value 0 to A. After that we are assigning 2. then enum will assign the incrementation of previous value. So C as the value 3.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

C allows you to use constant expressions to define enum values. Since using enum values, along with numeric constants, in an expression produces a constant expression, you can do this:

enum hello {
    A // You can assign zero explicitly, or let the compiler do it for you
,   B = A + 2
,   C // Again, you can assign B+1, or let the compiler do it for you
};

Upvotes: 2

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

Just do this

enum X
{
    A = 0,
    B = A + 2,
    C = B + 2
};

If you want to increment by 2 each time or if you want to do it only the first time

enum X
{
    A = 0,
    B = A + 2,
    C = B + 1
};

Note that the first will be 0 automatically so A = 0 is not needed it is in my answer just to make it explicit that A == 0, and in the second case and since the default increment will be 1 it is also not necessary to write C = B + 1, if you apply this to the code, it would look like

enum X
{
    A,
    B = A + 2,
    C
};

And you can ofcourse assign a value to each enum, like

enum X
{
    A = 0,
    B = 2,
    C = 3,
};

Upvotes: 3

Related Questions