【问题标题】:How to create a macro on a condition inside a if statement如何在 if 语句中的条件上创建宏
【发布时间】: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&gt;r; } int (*cmpFuncPtr)(int, int) = gt; int main() { while( cmpFuncPtr(1, 2) ) ; } 没有测试这个,但应该是一个带有微小修改的无限循环。类似地为小于或等于等定义函数,并根据您的需要将函数指针动态切换到其中之一。
  • 只要使repeated code -> repeatedCode() 即,使它成为一个函数。用宏选择迭代方向会让你的代码很难理解。

标签: c macros operators overloading


【解决方案1】:

您只需要循环代码一次。只需更改步长值和终止值即可。例如:

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;
}

【讨论】:

  • 我喜欢这个。我没有考虑将步骤更改为负数。我会尝试改变条件,看看它是否对我有用:)
  • 这个是解决方案,但考虑将repeatedCode() 设为一个函数,这样代码的作用会更清晰。
猜你喜欢
  • 2022-01-18
  • 1970-01-01
  • 2023-02-03
  • 1970-01-01
  • 2016-02-28
  • 2014-11-23
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
相关资源
最近更新 更多