Puzzled about for loops in C

66 views Asked by At

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?

3

There are 3 answers

1
abhiarora On BEST ANSWER

An expression represents a single data item--usually a number. The expression may consist of a single entity, such as a constant or variable, or it may consist of some combination of such entities, interconnected by one or more operators. Expressions can also represent logical conditions which are either true or false. However, in C, the conditions true and false are represented by the non-zero integer values and zero integer value, respectively. Several simple expressions are given below:

a + b
x = y
t = u + v
x <= y
++j

In your example, i is an expression whose value is expression's l-value which is in this case, it is the value of variable i. The expression will evaluate to true for non-zero i values and false if value of i is zero.

So, for(i=(size-1); i ; i--) is equivalent to for(i=(size-1); i != 0; i--).

0
AvaLanCS On

In C when trying to evaluate a condition, everything that is 0 is false, and everything else is true.

Even pointers are treated the same way. The constant NULL is actually defined as 0. In C++11 we finally have the null_ptr for type safety.

In C there is no bool type, and in C++ if you cast true to integer you get 1, and false casts to 0.

3
Rushy Panchal On

i by itself is converted to a boolean, similar to if (i) {...} or if (! i) {...}; integers are considered true when nonzero and false when zero.

So, for(i=size-1 ; i ; i--) is equivalent to for(i=size-1 ; i != 0; i--).