I would like to create an enumerated list of negative values for error handling so <0 is an error and >=0 is valid for some function:
int f() {
if (someerror())
return ERR_TYPE_2;
else
return 0;
}
main() {
if (f() < 0) blow_up();
else profit();
}
I know that enumerations in C (enum
) count up from 0 by default, and I could assign them like so:
enum {
ERR_TYPE_1 = -1,
ERR_TYPE_2 = -2,
ERR_TYPE_3 = -3
}
or I get arbitrary negative enums "automatically" by starting at an arbitrary negative value for which the enum will never reach:
enum {
ERR_TYPE_1 = -100,
ERR_TYPE_2 // -99
ERR_TYPE_3 // -98 ...
}
Question: Is there a way to tell enum
to start at -1
and count negative instead of using the methods above?
Update for commenters:
I have no objection to hard-coded error values, in fact that's what I usually do (either as a define or an enum).
This question is really about whether C officially supports negative enums in some unknown-to-me syntactic sugar that wasn't forthcoming after some search-fu.
What you want is not possible. Enum identifiers without an explicit value assigned are required to have the value of 1 more that the prior identifier, or 0 for the first one.
This is spelled out in section 6.7.2.2p3 of the C standard regarding Enumeration Specifiers:
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.
While it's possible that a compiler may support a different ordering as an extension, I'm not aware of any that support such a feature.