Reputation: 29
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;
}
}
Upvotes: 1
Views: 91
Reputation:
Because due to the short-circuiting property of the &&
operator, the modified code (your "working" version, that doesn't really work) would most likely invoke undefined behavior by accessing the -1th element in the array.
Upvotes: 3
Reputation: 477040
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.
Upvotes: 1