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
constant
orvariable
, or it may consist of some combination of such entities, interconnected by one or more operators. Expressions can also represent logical conditions which are eithertrue
orfalse
. However, in C, the conditionstrue
andfalse
are represented by the non-zero integer values and zero integer value, respectively. Several simple expressions are given below:In your example,
i
is an expression whose value is expression'sl-value
which is in this case, it is the value of variablei
. The expression will evaluate totrue
for non-zeroi
values andfalse
if value ofi
is zero.So,
for(i=(size-1); i ; i--)
is equivalent tofor(i=(size-1); i != 0; i--)
.