From: "M. Darland" Newsgroups: comp.os.msdos.djgpp Subject: Re: For loop problem Date: Mon, 6 Apr 1998 10:18:40 -0500 Organization: University of Texas at Arlington Lines: 31 Message-ID: References: <3527FEA6 DOT 54FA AT vegas DOT infi DOT net> NNTP-Posting-Host: omega.uta.edu Mime-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII In-Reply-To: <3527FEA6.54FA@vegas.infi.net> To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk On Sun, 5 Apr 1998, Simz wrote: > When ever I try to use a for loop in DJGPP with a char (or any type for > that matter), the loop never stops when I try to loop to the max value > that type can hold. For example > > unsigned char index = 0; > unsigned char array[256]; > for (index = 0; index < 256; index++) > array[index] = index; > > This loop never stops, I've even tried.. > for (index = 0; index <= 255; index++) > for (index = 0; index < 256; ++index) > for (index = 0; index <= 255; ++index) > > And I need all 256 iterations for my programs to work. > Any sugestions? > > Simz > tsim AT vegas DOT infi DOT net > > Since unsigned char can only hold values from 0-255, when the loop reaches 255 and increments, it 'increments' to 0. Not 256. So the condition to stop at >255 will never occur. i.e. here is the binary representation of 255( using unsigned char format), 11111111. Add 1 and you get 00000000. The for loop is going from 0->255,0->255... The solution: use an unsigned short int( or larger ) instead.