浮点常数比较 - (0.0?1:0)

bol*_*eto 12 c windows floating-point visual-studio

在下面的例子中,如果取消注释float f = 0.0;,
和更换return(0.0 ? 1 : 0);用return(f ? 1 : 0);.
输出是NIL.

这是我的代码:

/* file main.c 
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86
cl -W4 -MTd -O2 -TC main.c -Fetest */   
#include <stdio.h>    
int my_func(void)
{
   /* float f = 0.0; */
   return(0.0 ? 1 : 0);
}
int main(void)
{  
    printf("%s\n", ( my_func() ? "ONE" : "NIL") );
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在32位Windows计算机上,使用Visual Studio,此代码输出:

ONE
Run Code Online (Sandbox Code Playgroud)
  • 为什么my_func()返回值true(1)?
  • C编译器如何解释这个表达式(0.0 ? 1 : 0)?

Mar*_*som 8

这看起来像是Microsoft编译器中的一个错误,您应该将其提交给Connect.我能够在Visual Studio Express 2010中复制它,但不能在gcc中复制它:http://ideone.com/8qPRJd.

任何求值为整数值的表达式都0应该等效于false.这正是它如何处理float变量,当我尝试使用变量时double也是如此.