我需要遍歷嵌套在while
循環內的for
循環,以獲得幾種不同的條件。如何在if語句中的條件內創建宏
每個語句的代碼的唯一更改是要應用的比較條件。
原來我複製粘貼所有的代碼多次,並改變大於符號的方向。
例如:
if (direction.horizontal == UIScrollDirectionLeft) {
int column = startColumn+1;
while (column < maxAllowed) {
for (int row = minRow; row < maxRow; row++) {
repeated code
}
column++;
} else {
int column = minColumn -1;
while (column >= 0) {
for (int row = minRow; row < maxRow; row++) {
repeated code
}
column--;
}
}
是否有可能做條件運算符宏以便於代碼重用?
我真的很喜歡的東西可能是這樣的:
int startColumn = (direction.horizontal == UIScrollDirectionLeft) ? (startColumn+1) : minColumn -1;
SignOfOperator theSignInTheWhile = (direction.horizontal == UIScrollDirectionLeft) ? "<" : ">=";
int conditionToTestInWhile = (direction.horizontal == UIScrollDirectionLeft) ? maxAllowed : 0;
while(startColumn,theSignInTheWhile,conditionToTestInWhile) {
// repeated code
}
我有另外4個情況下,像上面的一個...
爲什麼不使用指向比較函數的指針? – 2015-02-11 14:11:46
該函數需要返回一個>或<=符號。比較是在我已經有的代碼中完成的 – 2015-02-11 14:12:50
不,函數會做比較;像'int gt(int l,int r){return l> r; } int(* cmpFuncPtr)(int,int)= gt; int main(){while(cmpFuncPtr(1,2)); }'沒有測試這個,但應該是一個無限循環,稍作修改。類似地定義少或相等的函數,並根據您的需要動態地將函數指針切換到其中的一個。 – 2015-02-11 14:16:45