Sandeep
Sandeep

Reputation: 33

What Is default datatype of constant numbers in c?

float x=2, y=2.6;

if(x==2); 
if(x==2.0) //both these conditions evaluate to be true

But,

 if(y==2.6); 

evaluates as false

Can anyone explain what's the default datatype of constant numbers and why am I getting such results

Upvotes: 3

Views: 236

Answers (2)

pmg
pmg

Reputation: 108986

float x=2, y=2.6;
//           ^^^ double, internally converted to float during the initialization
//      ^ int, internally converted to float during the initialization

if (x == 2) // compare double converted from float (x) with double converted from int (2)
if (x == 2.0) // compare double converted from float (x) with double (2.0)

if (y == 2.6) // compare double converted from float (y) with double (2.6)

Note about the last condition: initially 2.6 (a double) was converted to float; converting that float back to double does not guarantee the same value.

(double)(float)2.6 != 2.6

It goes kinda like this:

                 2.6 is 0b10.1001100110011001100110011001100110011001100110011001
          (float)2.6 is 0b10.10011001100110011001100
  (double)(float)2.6 is 0b10.1001100110011001100110000000000000000000000000000000
          difference is                             ^ approx. ~0.000000095367

Upvotes: 7

Vlad from Moscow
Vlad from Moscow

Reputation: 311146

The float constant 2.6 has the type double. To make the constant having the type float you should use the suffix f as 2.6f. As the size of the type float is less than the size of the type double then values in an object of the type float are less accurate represented than in an object of the type double.

Consider the following demonstrative program

#include <stdio.h>

int main(void) 
{
    float x = 2.6f,  y = 2.6;

    printf( "x == 2.6f -> %d\n", x == 2.6f );
    printf( "y == 2.6 -> %d\n", y == 2.6 );

    return 0;
}

Its output is

x == 2.6f -> 1
y == 2.6 -> 0

Upvotes: 2

Related Questions