Bug 26000 - cast from int to float violates C++ standard in non-optimized mode
Summary: cast from int to float violates C++ standard in non-optimized mode
Status: RESOLVED DUPLICATE of bug 323
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 4.0.2
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
Depends on:
Reported: 2006-01-28 02:53 UTC by Patrick Rabau
Modified: 2006-01-28 03:56 UTC (History)
40 users (show)

See Also:
Host: ?
Target: i686-pc-linux-gnu
Known to work:
Known to fail:
Last reconfirmed:


Note You need to log in before you can comment on or make changes to this bug.
Description Patrick Rabau 2006-01-28 02:53:19 UTC
Platform: i686 Linux 2.6.11

gcc version:
> gcc -v
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-libgcj-multifile --enable-languages=c,c++,objc,java,f95,ada --enable-java-awt=gtk --with-java-home=/usr/lib/jvm/java-1.4.2-gcj- --host=i386-redhat-linux
Thread model: posix
gcc version 4.0.2 20051125 (Red Hat 4.0.2-8)

According to the C++ standard section 5.2.9/2, the result of casting an
expression to float is as if a temporary variable of type float were 
declared and initialized with that expression, and then used in place 
of the expression.

That seems to be violated in the program below when compiled in non debug mode (gcc test.c)  The program a.out prints 1 instead of 0.
In optimized mode (gcc -O test.c) the program prints 0 correctly.  Same thing with -O2.

Same result when renaming the file test.cpp and compiling with g++ and also when using static_cast instead of C-style casts.

In the program below, the functions foo1() and foo2() should always produce the same result.  But the assembly code for foo2() differs from foo1() by two extra lines (fstps and flds) when compiled in non-optimized mode.


int foo1(int x)
   return (int)(float)x;

int foo2(int x)
   float f = x;
   return (int)f;

int main()
   int i = 0x1000001;   /* i == 16777217 */
   int u = foo1(i) - foo2(i);
   printf("u=%d\n", u);
Comment 1 Andrew Pinski 2006-01-28 03:56:02 UTC
this is a dup of bug 323.  The issue is more complex than you think, even though in this case you get the same answer for the optimized case and not for the unoptimized case.  Using -ffloat-store will get you a zero for the unoptimized case.

*** This bug has been marked as a duplicate of 323 ***