2015-02-11 107 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