-2

I have a type defined e.g.:

typedef enum {
 T1,
 T2,
 T3,
 T4,
 T5,
 T6,
 LAST_IN_ENUM
} type1_t;

then another one using the above type e.g.:

typedef enum {
 SUB1 = T1,
 SUB2 = T2,
 SUB3 = T3,
 SUB4 = T4
} type2_t;

I would like to use then some fields of type2_t as input parameters to a function, but referring to its last character from a loop variable value, e.g. for SUB2 and SUB3:

for (i=2; i<4; i++) {
 function1(SUBi)
}

What I don't know what the proper syntax is to pass the loop variable value to make it up SUBx (the above for loop syntax doe snot work, obviously).

Thanks a lot in advance if you have the solution.

I tried casting, converting to string, none of them worked.

Lorinc
  • 1
  • 1
  • 2
    Try `for( i = SUB2; i < SUB4; i++ )` The enum tokens are no more that compile time tokens that represent integer values. They are not runtime variables for accessing or manipulating. – Fe2O3 Jan 13 '23 at 10:50
  • 1
    I don't think you can construct a variable on-the-fly in this way in `C`. You could just create an array with the appropriate `SUB` values in the corresponding index location within the array. – Matt Pitkin Jan 13 '23 at 10:51
  • Take a look at this: https://stackoverflow.com/questions/16844728/converting-from-string-to-enum-in-c – Fabio_MO Jan 13 '23 at 10:53
  • Thanks for the answers. It seems inserting the loop variable value into the enum is not possible. – Lorinc Jan 13 '23 at 12:18

1 Answers1

0

You cant, I am afraid

You can only (if values are consecutive):

void bar(type2_t t2);

void foo(void)
{
    for(type2_t t = SUB1; t <= SUB4; t++)
    {
        bar(t);
    }
}

Or if they are not:

typedef enum {
 T1 = 5,
 T2 = 35,
 T3 = 65,
 T4 = 999,
 T5,
 T6,
 LAST_IN_ENUM
} type1_t;

typedef enum {
 SUB1 = T1,
 SUB2 = T2,
 SUB3 = T3,
 SUB4 = T4
} type2_t;

void bar(type2_t t2);

void foo(void)
{
    const type2_t t2Table[] = {SUB1, SUB2, SUB3, SUB4};
    for(size_t t = 0; t < sizeof(t2Table) / sizeof(t2Table[0]); t++)
    {
        bar(t2Table[t]);
    }
}
0___________
  • 60,014
  • 4
  • 34
  • 74
  • Thanks, the 2nd solution is closer already what I need, it seems that the way that seemed to be the most useful (inserting the value of the loop variable) is not possible unfortunately. – Lorinc Jan 13 '23 at 11:35