Just to be clear, I understand how for loops work. However, the different syntax causes me problems... Let me give you an example:
I was looking up a recursive sorting algorithm (insertion sort). The code went like this:
void insertion_recursive(int array[],int size){
int i;
if (size<=1) return;
insertion_recursive(array,size-1);
for(i=size-1;i;i--)
if(array[i]<array[i-1])
swap(&array[i],&array[i-1]);
else
break;
}
I understand how the code works, but the condition for the loop is confusing me:
for(i=size-1 ; i ; i--)
What does it mean? Just leaving 'i' without specifying a condition?
An expression represents a single data item--usually a number. The expression may consist of a single entity, such as a
constantorvariable, or it may consist of some combination of such entities, interconnected by one or more operators. Expressions can also represent logical conditions which are eithertrueorfalse. However, in C, the conditionstrueandfalseare represented by the non-zero integer values and zero integer value, respectively. Several simple expressions are given below:In your example,
iis an expression whose value is expression'sl-valuewhich is in this case, it is the value of variablei. The expression will evaluate totruefor non-zeroivalues andfalseif value ofiis zero.So,
for(i=(size-1); i ; i--)is equivalent tofor(i=(size-1); i != 0; i--).