public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
From: John Love-Jensen <eljay@adobe.com>
To: Sam Ravnborg <sam@ravnborg.org>, MSX to GCC <gcc-help@gcc.gnu.org>
Subject: Re: cast of float to unsigned char bug on ARM with 3.4.5 - when  was it fixed?
Date: Thu, 10 Jan 2008 15:23:00 -0000	[thread overview]
Message-ID: <C3AA2D95.29E2D%eljay@adobe.com> (raw)
In-Reply-To: <20080108212505.GA27307@uranus.ravnborg.org>

Hi Sam,

> I assume this is a know bug that got fixed in later gcc's.
> I have tried searching the gcc bug database with no luck.

It's not a GCC bug.  Your code a C bug (if I may be so presumptuous to
describe using undefined C behavior as a "bug").

Since your code is performing undefined behavior, the output of all four
examples is correct.

From "The C Programming Language" A.6.3 "The result is undefined if the
value will not fit in the space provided".  After truncation, -30 does not
fit in 0 ... 255 range (assuming your unsigned char is 8-bit), hence
undefined behavior.

One way you could fix your code to have more consistent behavior is to use
an intermediate int.

The sample code:
====================
#include <stdio.h>

int main(void)
{
  int i;
  unsigned char n1;
  float n2;

  n2 = -30.33F;
  i = (int)n2;
  n1 = (unsigned char)i;

  printf("n1: %d n2: %3.2f\n", n1, n2);

  return 0;
}
====================

As long as an int is the same bit-size and is 2's complement represented on
the platforms being compared, that should product the same output.

HTH,
--Eljay

  reply	other threads:[~2008-01-09 13:52 UTC|newest]

Thread overview: 3+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2008-01-09 16:29 Sam Ravnborg
2008-01-10 15:23 ` John Love-Jensen [this message]
2008-01-10 19:57   ` Sam Ravnborg

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=C3AA2D95.29E2D%eljay@adobe.com \
    --to=eljay@adobe.com \
    --cc=gcc-help@gcc.gnu.org \
    --cc=sam@ravnborg.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).