Is there a way to use pointers inside C-switch statements?

Typically, in a dynamically typed programming language, a struct object has a tag field used to identify the type of object. For instance:

struct myObject {
    int tag;
    ...
}

Thus, it is easy to perform various actions using the switch statement based on the tag field. For instance:

switch (obj->tag) {
    case OBJ_INTEGER: ...
    case OBJ_STRING: ...
    case OBJ_FUNC:...
}

In my case, instead of the int tag field, I used the void * isa pointer, which points to the class that this object represents. Everything worked fine, expecting that instead of using the elegant switch statement, I have to use a series of if / else statements. For instance:

if (obj->isa == class_integer) {
    ...
} else if (obj->isa == class_string) {
    ...
} else if (obj->isa == class_func) {
    ...
}

I know that I cannot use pointers inside C-switch statements, but I am wondering if I can use some kind of smart trick to speed up a series of if statements.

+4
1

isa - switch.

:

switch (obj->tag) {
    case OBJ_INTEGER: do_something_int(obj); break;
    case OBJ_STRING: do_something_str(obj); break;
    case OBJ_FUNC: do_something_func(obj); break;
}

, isa struct, - , struct dyn_type. struct, :

typedef void (*ProcessPtr)(dyn_obj * obj);

struct dyn_type {
    ... // fields of your current struct
    ProcessPtr process;
};

process do_something_int OBJ_INTEGER, do_something_str OBJ_STRING .. switch

((struct dyn_type*)obj->isa)->process(obj)
+14

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


All Articles