2015-02-11 31 views
1

我需要遍歷嵌套在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個情況下,像上面的一個...

+1

爲什麼不使用指向比較函數的指針? – 2015-02-11 14:11:46

+0

該函數需要返回一個>或<=符號。比較是在我已經有的代碼中完成的 – 2015-02-11 14:12:50

+0

不,函數會做比較;像'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

回答

2

你只需要一次循環代碼。只需更改步驟值和終止值。例如:

int start_column, end_column, column_step; 
    : 
switch (direction.horizontal) { 
    case UIScrollDirectionLeft: 
    column = start_column + 1; 
    column_step = 1; 
    end_column = max_allowed; 
    break; 
    case UIScrollDirectionRight: 
    column = min_column - 1; 
    column_step = -1; 
    end_column = -1; 
    break; 
    : 
} 
while (column != end_column) { 
    for (int row = minRow; row < maxRow; row++) { 
    repeated_code(); 
    } 
    column += column_step; 
} 
+0

我喜歡這個。我沒有考慮將這一步改爲否定。我會嘗試改變條件,看看它是否可以爲我工作:) – 2015-02-11 14:20:12

+1

這是一個解決方案,但考慮製作'repeatCode()'函數,這樣會更清楚代碼的作用。 – 2015-02-11 14:30:43