简体   繁体   English

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

[英]floating-point constant comparison - (0.0 ? 1 : 0)

In the example below, if uncomment float f = 0.0; 在下面的示例中,如果取消注释float f = 0.0; ,
and replacing the return(0.0 ? 1 : 0); 并替换return(0.0 ? 1 : 0); with return(f ? 1 : 0); return(f ? 1 : 0); .
The output is NIL . 输出为NIL

Here is my code: 这是我的代码:

/* 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;
}

On a 32-bit Windows machine, using Visual Studio this code outputs : 在32位Windows计算机上,使用Visual Studio,此代码输出:

ONE
  • Why my_func() returns value true (1) ? 为什么my_func()返回值true (1)?
  • How does the C compiler interpret this expression (0.0 ? 1 : 0) ? C编译器如何解释这个表达式(0.0 ? 1 : 0)

This looks like a bug in the Microsoft compiler which you should submit to Connect . 这看起来像是Microsoft编译器中的一个错误,您应该将其提交给Connect I was able to duplicate it in Visual Studio Express 2010, but not in gcc: http://ideone.com/8qPRJd . 我能够在Visual Studio Express 2010中复制它,但不能在gcc中复制它: http//ideone.com/8qPRJd

Any expression that evaluates to an integer value of 0 should be equivalent to false . 任何求值为0的整数值的表达式都应该等于false This is exactly how it's working with the float variable, and it's the same when I tried it with a double as well. 这正是它如何使用float变量,当我尝试使用double也是如此。

return(0.0?1:0)编译为固定返回1.在另一种情况下,实际评估浮点变量,0.0不等于0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM