www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/07/05/23:04:58

From: Erik Max Francis <max AT alcyone DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Newbie for loop/data type problem
Date: Sat, 05 Jul 1997 17:02:17 -0700
Organization: Alcyone Systems
Lines: 57
Message-ID: <33BEE089.60401C2C@alcyone.com>
References: <33B4CBA2 DOT 40D6 AT lausd DOT k12 DOT ca DOT us>
NNTP-Posting-Host: newton.alcyone.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

csantill wrote:

> I'm having a problem w/a stupid for loop(or maybe I have newbie luck & I
> just found a bug in GCC v2.72).  Ok, I know chars are byte values, but
> they seemed to be signed in DJGPP (ANSI C dictates that they are
> unsigned; but then again, DJGPP isn't ANSI C or ANSI anything else for
> that matter).

ANSI C, 6.2.1.1:

    As discussed earlier, whether a "plain" [meaning not specifically
    referred to as signed or unsigned] char is treated as signed is
    implementation-defined.

ANSI C does not guarantee that a char is unsigned; in fact, it
specifically indicates that it doesn't say whether it is or not.

Furthermore, gcc is by far and away in my experience the most ANSI C
compliant C compiler I've used.

> When I change the RHIDE flag option so that GCC compiles
> chars as unsigned bytes I lose a *warning* about something like "data
> type limitation".  But, w/the unsigned char flag on, I get an infinite
> loop(this pisses me off because I call this function from another
> function).  If anybody has a work around (while loop, a mix of C wrapped
> in an inline ASM loop) or any other help would be great;

Even with an unsigned char iteration variable (and specifying the values
as unsigned with the U suffix), this won't work; the reason is because
when incrementing c (as unsigned) when it's 255u, the incremented value
will be 0u.  This means that the loop will continue on forever, just as in
the signed case.

An awkward way to get around this is to use a do...while loop:

    unsigned char c = 0;

    do {
        /* ... */
    } while (++c);

The solution is to just use an int:

    int c;

    for (c = 0; c < 256; c++)
        /* ... */

and whenever you need to refer to the value, cast it to an unsigned char.

-- 
       Erik Max Francis, &tSftDotIotE / email / max AT alcyone DOT com
                     Alcyone Systems /   web / http://www.alcyone.com/max/
San Jose, California, United States /  icbm / 37 20 07 N  121 53 38 W
                                   \
           "All the gods are dead / except the god of war."
                                 / Eldridge Cleaver

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019