That is nasty code!
It's always a bad idea to have a construct like this:
for (...);
printf(...);
because is't very difficult to see the ";" at the end of the
for
loop - so it looks to a casual eye like you wrote this:
for(...)
{
printf(...);
}
Which would have very different results. In fact, modern compilers will complain or at least warn you about it because it does cause a lot of confusion.
So start by restructuring your code:
int main()
{
int x = -3, y = 0, k, j;
for( k = j = -3 ; ++j ; y += 2)
{
x = x + (k < j);
}
printf("x=%d y=%d k=%d j=%d",x,y,k,j);
return 0;
}
Now it's easier to read and a lot more obvious what is going on.
1) Preset x to -3, y to 0.
2) Preset k and j to -3.
3) Enter the loop.
3.1) Compare k and j.
3.1.1) If k is less than j, add one to x (Remember, in C the result of any logical operation is zero for false, or one for true, so
k < j
returns 0 or 1)
3.1.2) Otherwise, add zero to x.
3.2 Add 2 to y
3.3 Add one to j, and if that value is nonzero, loop back round to (3).
4) Print the results.
See how much easier it is to read and understand when you write it out properly?
It's still nasty code though: I'd prefer to see either this:
int main()
{
int x = -3, y = 0, k, j;
for( k = j = -3 ; ++j ; y += 2)
{
if (k < j)
{
x++;
}
}
printf("x=%d y=%d k=%d j=%d",x,y,k,j);
return 0;
}
Or this:
int main()
{
int x = -3, y = 0, k, j;
for( k = j = -3 ; ++j ; y += 2)
{
x += (k < j) ? 1 : 0;
}
printf("x=%d y=%d k=%d j=%d",x,y,k,j);
return 0;
}
Where the values you are playing with are more explicit.