1

I have a function that returns a float number:

float function(enum value)

I then have an enum

typedef enum
{
    a = 0,
    b,
    c
} myenum;

I want to do the following:

function(a+1);

And I wonder if there are any risks other than the risk of unexpected behaviour if the enum changes. My question might seem dumb but I have to make sure that there are no risks of what I'm doing.

Please don't ask questions on why it's done like this. Because I don't know. I just need to know if it's safe or not.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
user3660570
  • 337
  • 1
  • 14
  • You have your answers, the code shown doesn't have any problems, still, if you don't know *why* you are doing something, that's often asking for trouble... (I don't want to know why, just saying *you* really *should* know) –  Jun 20 '17 at 14:05
  • You could steal this trick for [creating type-safe enums](https://stackoverflow.com/questions/43043246/how-to-create-type-safe-enums). – Lundin Jun 20 '17 at 14:14

2 Answers2

4

This is safe. Moreover, the standard guarantees that a+1 is b and a+2 is c in the scenario that you describe:

C99 standard, section 6.7.2.2, part 3: If the first enumerator has no =, the value of its enumeration constant is 0. Each subsequent enumerator with no = defines its enumeration constant as the value of the constant expression obtained by adding 1 to the value of the previous enumeration constant.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

It's safe. As you seem to recognise yourself, it's really working against the way enums are intended to work, which is as arbitrary labels. However sometimes you want ordering such that a < b < c. If a = 0 and b = 1 and c = 2 in some firm sense, then you don't want an enum, however, you want a variable of type int.

Malcolm McLean
  • 6,258
  • 1
  • 17
  • 18