3

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.

4

1 に答える 1

5

あなたは簡単に行うことができます

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

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

expensive complicated call外部関数に入れ、if条件内の 2 つの場所から callitすることもできます。

int myExpensiveAndComplicatedCall() {
    // Do things
}

if (i < SIZE_OF_V) {
    if (V[i])
        K = V[d];
    else
        K = V[d] = myExpensiveAndComplicatedCall();
} else {
    K = myExpensiveAndComplicatedCall();
}
于 2012-11-21T19:56:14.053 に答える