Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRY caching in C

Tags:

c

memoization

dry

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.

like image 454
Charles Avatar asked Mar 11 '26 08:03

Charles


1 Answers

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();
}
like image 146
alestanis Avatar answered Mar 13 '26 04:03

alestanis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!