Change enumeration values ​​at runtime?

Is there a way to assign values ​​for enumerations at runtime in object c? I have several transfers and I want each of the transfers to have a certain value. Values ​​can be read from an XML file. Is there any way to do this?

+6
source share
2 answers

Unfortunatley, @Binyamin is right, you cannot do this with a listing. For this reason, I usually do the following in my projects:

// in .h typedef int MyEnum; struct { MyEnum value1; MyEnum value2; MyEnum value3; } MyEnumValues; // in .m __attribute__((constructor)) static void initMyEnum() { MyEnumValues.value1 = 10; MyEnumValues.value2 = 75; MyEnumValues.value3 = 46; } 

This also has the advantage of being able to iterate over values, which is not possible with a normal enumeration:

 int count = sizeof(MyEnumValues) / sizeof(MyEnum); MyEnum *values = (MyEnum *) &MyEnumValues; for (int i = 0; i < count; i++) { printf("Value %i is: %i\n", i, values[i]); } 

All in all, this is my preferred way to do enumerations in C.

+16
source

No, enumeration information is deleted at compile time.

+5
source

Source: https://habr.com/ru/post/914069/


All Articles