DRY caching in C

c, dry, memoization

Solution

You can simply do

if (i < SIZE_OF_V && V[i]) {
    K = V[d];
} else {
    K = (expensive complicated call);

    if (i < SIZE_OF_V)
        V[d] = K;
}

You can also put your `expensive complicated call` in an external function and callit from two places inside your `if` conditions:

int myExpensiveAndComplicatedCall() {
    // Do things
}

if (i < SIZE_OF_V) {
    if (V[i])
        K = V[d];
    else
        K = V[d] = myExpensiveAndComplicatedCall();
} else {
    K = myExpensiveAndComplicatedCall();
}

Problem

I'm looking to DRY out the following C code: ``` if (i < SIZE_OF_V) { if (V[i]) K = V[d]; else K = V[d] = (expensive complicated call); } else { K = (expensive complicated call); } ``` Any advice? A local macro would work, but I'd prefer a more modern alternative.

Original source