Search code examples
cpointersfunction-pointers

Sequential Execution of functions with break option


I have a thread in my operating system that is called in a fixed interval and then executes a list of 10-15 distinct functions sequentially. Each function has a return parameter that either says 0 (OK) or not 0 (error). Looks something like this:

while (1) {
    error &= function_1();
    error &= function_2(some_parameter);
    error &= function_3();
    handleError(error);
}

However it would be preferred that when one of the functions returns an error, the error is handled immediately and the other functions are not being executed anymore (single error failure).

For two functions I could do an if condition before each function but for 10-15 that would lead to a lot of unnecessary ifs.

For that I would use an array of function pointers that I go through sequentially:

int (*p_functions[3])() = { function_1, function_2, function_3 }
while (1) {
    for (int i = 0; i < 3, i++) {
        error = p_functions[i];
        if (error) {
            handle_error(error);
            break;
        }
    }
}

My issue here is that as you can see in the first example my function_2() has a parameter that gets maybe generated by another function beforehand. So I can't deal with functions that have different parameters.

Are there any other ways to solve that? Or maybe with some tricks for pointer casting? I heard dirty casting is a thing?


Solution

  • #define E(e,x)  e = (e ? e : x)
    while (1) {
        error = 0;
        E(error, function_1());
        E(error, function_2(some_parameter));
        E(error, function_3());
        handleError(error);
    }
    

    Isn't too bad; this is the style things like the SV test suite are written in; and the actual error value is preserved.