my doubt is a general C doubt.. we know if we are using enum the variables which we declare inside automatically increments by one than the previous variable.. but is there any method by which we could make the variables to decrement by one instead of incrementing...
Example
enum my_enum { var1=90, var2,var3 };
for this code var2 and var3 will be 91 & 92 respectively, is there any method (possible) to get them 89 & 88... It was asked in an interview.. any one knows the answer..?
"...An enumerated type is a user-defined type consisting of a set of named constants called enumerators. By default, the first enumerator has a value of 0, and each successive enumerator is one larger than the value of the previous one, unless you explicitly specify a value for a particular enumerator."
Greetings, Tamir Michael
The preprocessor seems a bit of overkill, unless you expect to change the way the enums hop. Today decrement by one, tomorrow all multiples of 3...
Just decrementing is sufficient.
typedef enum X { base = 90, primus = base - 1, secundus = primus - 1, tertius = tertius - 1 } X;
Any relative scheme is vulnerable to adding and deleting values, as all later values then shift.
It's often handy for later reference and debugging to explicitly assign all the values in a enum, even when they're in incrementing order anyway. This is especially useful for large enums like error codes or some protocol ID numbers. A declaration like
typedef enum X { base = 90, primus = 91, secundus = 92, tertius = 93 } X;
makes it really easy to find the value for a symbolic name, or conversely search for the value when you find it in a hex dump. Any relative method, including the preprocessor, makes this kind of lookup harder. And you don't have to worry about breaking half the values when you add a new one in the middle. It may be worth the tedium simply to list each value.
(And if it's really that huge of an enum, you could always write a little script to generate the C syntax given a list of identifiers.)
I see I neatly demonstrated one reason why you'd use the preprocessor ;)
Where's the edit button?
View all questions in Keil forum