-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.

4
  • 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. Commented Jan 13, 2023 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. Commented Jan 13, 2023 at 10:51
  • Take a look at this: stackoverflow.com/questions/16844728/… Commented Jan 13, 2023 at 10:53
  • Thanks for the answers. It seems inserting the loop variable value into the enum is not possible. Commented Jan 13, 2023 at 12:18

1 Answer 1

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]);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.