【发布时间】:2015-02-11 14:06:28
【问题描述】:
我需要针对几个不同的条件迭代嵌套在 while 循环内的 for 循环。
每个语句的代码中唯一的变化是应用的比较条件。
原来我正在多次复制粘贴所有代码并更改大于小于符号的方向。
例如:
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个类似上面的案例...
【问题讨论】:
-
为什么不使用指向比较函数的指针?
-
该函数需要返回一个 > 或
-
不,该函数会进行比较;像
int gt(int l, int r) { return l>r; } int (*cmpFuncPtr)(int, int) = gt; int main() { while( cmpFuncPtr(1, 2) ) ; }没有测试这个,但应该是一个带有微小修改的无限循环。类似地为小于或等于等定义函数,并根据您的需要将函数指针动态切换到其中之一。 -
只要使
repeated code->repeatedCode()即,使它成为一个函数。用宏选择迭代方向会让你的代码很难理解。
标签: c macros operators overloading