简体   繁体   中英

What's the difference between these two conditions?

The expression j > 0 && a[j - 1] > value_to_insert appears in the definition of the sort_ints function. Why would it not be acceptable to rewrite this as a[j-1] > value_to_insert && j > 0 ? I tried putting the condition the other way around and it gave me the same output as the original.

Here's the function definition:

void sort_ints(int *a, int n)
{
    int i;
    int j;
    int value_to_insert;

    for (i = 1; i < n; i++) {
        value_to_insert = a[i];

        /* Shift values greater than value_to_insert. */
        j = i;
        while (j > 0 && a[j - 1] > value_to_insert) {
            a[j] = a[j - 1];
            j--;
        }
        a[j] = value_to_insert;
    }
}

因为由于&&运算符的短路属性,修改后的代码(您的“工作”版本,实际上不起作用)很可能通过访问数组中的第-1个元素来调用未定义的行为。

It's undefined behaviour to evaluate a[-1] . Since the logical-AND operator && has short-circuited semantics, a[j - 1] is never evaluated if j == 0 in the original code.

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