Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) ?
like image 975
boleto Avatar asked Aug 02 '13 03:08

boleto


People also ask

What are floating-point constants?

A "floating-point constant" is a decimal number that represents a signed real number. The representation of a signed real number includes an integer portion, a fractional portion, and an exponent. Use floating-point constants to represent floating-point values that can't be changed.

Is 0 a float value?

A floating point number, is a positive or negative whole number with a decimal point. For example, 5.5, 0.25, and -103.342 are all floating point numbers, while 91, and 0 are not. Floating point numbers get their name from the way the decimal point can "float" to any position necessary.

What is the default format for floating constants?

The default type of a floating-point constant is double. You can also append the suffix F or f to assign a constant the type float, or the suffix L or l to give a constant the type long double, as this example shows: float f_var = 123.456F; // Initialize a float variable.


1 Answers

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.

like image 126
Mark Ransom Avatar answered Oct 28 '22 23:10

Mark Ransom