繁体   English   中英

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

[英]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;
}

在执行增强的赋值运算符/=后,它将对h求值,该运算符将h除以第二个操作数,并将结果分配回h
h为0时,条件将失败。

更具可读性的等效项是

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

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

该声明

h /= 2;

h除以2,将新值分配给h ,然后评估该新值。 因此,一旦由于重复除以2而使h变为0(并且最终将变为0),则条件将变为假,并且循环将结束。

如果某物为0,则为false;如果某物不为0,则为true。

所以h / = 2将继续除以h直到达到0,然后退出循环

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM