dis_is_ea...@yahoo.com wrote:
hi..i have a question on the execution of for loop...i think the order
of execution of the for loop is initialization,condition and
increment...but i couldnt understand the following questions....
Questions from where ? Has a "How to win the IOCCC" book
been published ?
1: int x=1,y=1;
for( ; y ; printf("%d %d",x,y))
y=x++<=5;
Have you tried to run it ? There are a number of things
happening here.
y=x++<=5 is parsed as y = (x++ <= 5)
which means that if x is <=5 then the expression (x++ <= 5)
is true which in C means that it has the value 1. So in this
case y takes the value 1. On the other hand, if x>5 then the
expression (x++ <= 5) is false which means that it has the
value 0 so y takes the value 0. The presence of ++ (as in x++)
means that the expression (x++ <= 5) will increase the value
of x by 1 as a side effect but note that the comparison between
x and 5 will happen **before** the increase.
This should get you started. Think and see if you can figure out
the rest on your own. Try also to experiment with different values
and see what happens.
2: short int i=0;
for( i<=5 && i>= -1 ; ++i ; i>0)
printf("%u",i);
This is easier. As far as I can see it will eventually overflow
i which means undefined behaviour. This can be fixed by
using unsigned short i=0;
In this case , when i reaches the maximum value for an unsigned
short and then gets increased , its value will become 0. Now remember
what I mentioned about 1 meaning "true" and 0 meaning "false" in C
and see if you can figure out what will happen.
Spiros Bousbouras