Fog Creek Software
Discussion Board




c question

i got asked a cute question (short check if the person knows c)

for(unsigned int i=100;i>=0;i--)
{
  dosomething();
}

where is the problem?
loop never stops, cause counter can't get to less than zero.

M.M.
Saturday, March 29, 2003

Use a signed integer.

Rob Kaper
Saturday, March 29, 2003

Even once you change the type of "i" to int, this loop will still run 101 times.  Still probably not what they want.

I usually like to write these as:

for (int  i= 100; i --; ) ...

But while this was really great on the 68000 (since there was a single instruction for decrement and branch if zero), modern compilers are really aweful at this.  In fact, in a test a year ago with gcc, the -O version was > 2X slower than the non -O version.

Derek Woolverton
Wednesday, April 09, 2003

There's also the little matter of the illegal declaration of i (in C89 at any rate) - declarations have to be at the start of a block.

Dave.

David Neary
Monday, April 14, 2003

*  Recent Topics

*  Fog Creek Home