我需要遍历嵌套在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