3

我正在寻找干燥以下C代码:

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

有什么建议吗?本地宏会起作用,但我更喜欢更现代的替代方案。

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条件内的两个位置调用:

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 回答