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..?
No, there isn't!
"my doubt is a general C doubt"
So you should look for your answer in a general 'C' textbook - or even the 'C' standard itself:
"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"
... enum my_num{var1=90,var2=89,var3=88}; printf("%d,%d,%d",var1,var2,var3); ...
Hello ninja, Did you bother to READ the previous posts? We stated clearly that it is possible if you assign the values yourself! But that was not what the original post asked!
Next step up is to play with the preprocessor.
#include <stdio.h> #define _(x) \ x##tmp1, \ x = base-(x##tmp1-base),\ x##tmp2 = x##tmp1 enum { base = 90, _(alt1), _(alt2), _(alt3) }; int main() { printf("%u %u %u %u\n",base,alt1,alt2,alt3); return 0; }
Impressively horrible. Note that the printf() format specifiers require the 'b' modifier for C51 (and ought to be 'd' rather than 'u').
I'm surprised nobody has suggested:
enum my_enum{var3=88, var2, var1};
or does that not fit with the spirit of the thing?
Well, it doesn't answer the specific question about having the compiler automatically assign decreasing values - although it does achieve the required end of the given example.
If I were the interviewer, I would certainly give credit for that!
Generally, interview questions aren't about showing what you know, but showing that you can think...
I tend to prefer a combination of both.
By the way, out here in the world wide jungle 'interview question' is a euphemism for 'homework question'.
View all questions in Keil forum