没有条件的条件是什么意思?

What does a conditional without a condition mean?

我正在尝试阅读一些 C 语言。有一个带有条件的 for 循环似乎不是条件。在for循环for (h = n; h /= 2;)中,条件是h/=2;。但这不是真话或假话。这是什么意思?这个for循环什么时候结束?

这是来自 http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort#C 的完整代码:

#include <stdio.h>

void shell_sort (int *a, int n) {
    int h, i, j, t;
    for (h = n; h /= 2;) {
        for (i = h; i < n; i++) {
            t = a[i];
            for (j = i; j >= h && t < a[j - h]; j -= h) {
                a[j] = a[j - h];
            }
            a[j] = t;
        }
    }
}

int main (int ac, char **av) {
    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
    int n = sizeof a / sizeof a[0];
    int i;
    for (i = 0; i < n; i++)
        printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
    shell_sort(a, n);
    for (i = 0; i < n; i++)
        printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
    return 0;
}

如果某项为 0,则为假,如果某项不为 0,则为真。

所以h/= 2会一直除h直到达到0,然后退出循环

声明

h /= 2;

h 除以 2,将新值赋给 h,然后计算新值。因此,一旦 h 由于重复除以 2 而变为 0(最终会如此),条件将变为假并且循环将结束。

它将在执行扩充赋值运算符 /= 后计算 h,它将 h 除以第二个操作数并将结果赋值回 h
h 为 0 时,条件将失败。

更易读的等价物是

int h = n, i, j, t;
while (h /= 2) {
    ...
}

for(h = n / 2; h; h /= 2) { ... } 也是等价的,但是为了有一个 for 循环而在初始化中重复增量显然很麻烦。