简体   繁体   中英

What does a conditional without a condition mean?

I am trying to read some C. There is a for loop with a conditional that does not appear to be a condition. In the for loop for (h = n; h /= 2;) , the conditional is h/=2; . But this is not a true or false statement. What does this mean? When does this for loop end?

Here is the full code from 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;
}

It will evaluate h after performing the augmented assignment operator /= , which divides h by the second operand and assigns the result back to h .
The condition will fail when h is 0.

A more readable equivalent would be

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

for(h = n / 2; h; h /= 2) { ... } is equivalent, too, but it's obviously messy repeating the increment in the initialisation just for the sake of having a for loop.

The statement

h /= 2;

divides h by 2, assigns that new value to h and then evaluates that new value. Hence, as soon as h becomes 0 due to repeated division by 2 (and it eventually will), the condition will become false and the loop will end.

if something is 0, its false, if something is not 0, its true.

so h/= 2 will keep dividing h until it reaches 0, then quit the loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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