c - 如何在 if 语句中的条件下创建宏

标签 c macros operators overloading

我需要针对几个不同的条件迭代嵌套在 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 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;
}

关于c - 如何在 if 语句中的条件下创建宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28456383/

相关文章:

c - 了解快速平方根反比中的指针语法

c - 使用长度为 0 的多维数组时出错

c - 在 C 中创建获取字符串函数时遇到问题

c - C中ListNode中的指针

c - typedef uintX_t 类型,其中 X 是宏的值

matlab - Matlab/Octave 是否支持对矩阵切片的操作?

c++ - 从工厂类创建对象名称的 undefined reference

c++ - 自动生成开关案例。或者另一个建议

c++ - 与 'operator=' 不匹配

c++ - C++ 中的指针否定 (!ptr == NULL)