[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: C programming



Quick answer here - I'll make two assumptions:

1) This is NOT for a programming assignment. ;-)

2) Using the comma within a condition is treated as AND (&&). That's
messier code than I usually create.

Making the z = x + y assignment is part of the loop's condition, so it is
evaluated at whatever the value is, in addition to the z > x. If the
assignment is does not evaluate to the same value (true or false) as the
>, it can change the number of times the loop cycles. Move z = x + y out
of the condition part of the for statement, and you will have the same
results from both loops.

Also, it depends on how decimal values evaluate into either true or false,
since that is what the z = x + y assigment gives to the condition. You can
write a little program to test that out, and it will probably answer your
question.

John

On Fri, 4 Aug 2000, Christophe TROESTLER wrote:

> I apologize if that is a little bit off topic but I am a bit puzzled
> and  I  know there  are  experts  on this  list.   I  would like  an
> explanation on why the two "for" below give different results.
> 
> Thanks,
> ChriS
> -.¸¸.·´¯`·.¸¸.-.¸¸.·´¯`·.¸¸.-.¸¸.·´¯`·.¸¸.-.¸¸.·´¯`·.¸¸.-.¸¸.·´¯`·.¸¸.-
> 
> #include <stdio.h>
> 
> main()
> {
>   double x, y, z;
>   int t;
>   
>   for(x=.5, y=1./4., t=1;   z= x + y, z > x;   y /=2,  t++)
>     ;
>   printf("t=%i\n", t);
> 
>   for(x=.5, y=1./4., t=1;  x+y > x;   y /=2,  t++)
>     ;
>   printf("t=%i\n", t); 
> }



Reply to: