[Info-vax] decrementing & for loops in C
Bill Gunshannon
billg999 at cs.uofs.edu
Thu Jan 8 09:19:00 EST 2009
In article <176uZD2KcidF-pn2-d8d17hV5X6v3 at rikki.tavi.co.uk>,
"Bob Eager" <rde42 at spamcop.net> writes:
> On Thu, 8 Jan 2009 13:03:32 UTC, vaxinf at chemie.uni-konstanz.de wrote:
>
>> int main (void) {
>>
>> int i,sum=0,n=10;
>>
>> (void)printf ("Starting countdown loop...\n");
>> (void)fflush (stdout);
>> for (i = n; i = 0; i--) {
>> (void)printf (" i: %i\n",i);
>> }
>> (void)printf ("done.\n");
>>
>> (void)printf ("Starting normal loop...\n");
>> (void)fflush (stdout);
>> for (i = 1; i <= n; i++) {
>> (void)printf (" i: %i\n",i);
>> }
>> (void)printf ("done.\n");
>> }
>>
>> Here is the output:
>>
>> r SYSWRITE_TST
>> Starting countdown loop...
>> done.
>> Starting normal loop...
>> i: 1
>> i: 2
>> i: 3
>> i: 4
>> i: 5
>> i: 6
>> i: 7
>> i: 8
>> i: 9
>> i: 10
>> done.
>>
>> So the countdown loop is ignored. g++ under linux behaves the same.
>
> There's a logical error in the code. The second part of if() is the
> condition to be fulfilled to keep the loop going (see the normal loop,
> where it's going to keep going as long as i is less than or equal to n).
>
> So it says:
>
> for (i = n; i = 0; i--) {
>
> (i.e. "keep going as long as i is zero", which it obviously isn't)
>
> It should be:
>
> for (i = n; i != 0; i--) {
>
> (i.e. "keep going as long as i is not zero")
See my previous post. It does not say "keep going as long as i is zero"
because you used the assignment operator instead of the comparison operator.
It says "set i to 0 and return success" and that terminates the loop.
bill
--
Bill Gunshannon | de-moc-ra-cy (di mok' ra see) n. Three wolves
billg999 at cs.scranton.edu | and a sheep voting on what's for dinner.
University of Scranton |
Scranton, Pennsylvania | #include <std.disclaimer.h>
More information about the Info-vax
mailing list