简体   繁体   中英

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

In the example below, if uncomment float f = 0.0; ,
and replacing the return(0.0 ? 1 : 0); with return(f ? 1 : 0); .
The output is 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 :

ONE
  • Why my_func() returns value true (1) ?
  • How does the C compiler interpret this expression (0.0 ? 1 : 0) ?

This looks like a bug in the Microsoft compiler which you should submit to Connect . I was able to duplicate it in Visual Studio Express 2010, but not in gcc: http://ideone.com/8qPRJd .

Any expression that evaluates to an integer value of 0 should be equivalent to 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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