Hi guys ,

In Visual Studio 2005 I compiled the following code

int main()
{
	float a;
	a=0.1; 

	if(a<0.1)
	{ 
		printf("C\n");
	}
	else
	{
		printf("C++\n");
	}
}

I was very surprised when I saw the output C++ .
I got the warning C4305 :" '=' : truncation from 'double' to 'float' " , I searched the web but couldn't find some answers .

I don't understand what's wrong with assigning the value 0.1 to a float variable .

Thank you

Recommended Answers

All 7 Replies

>I don't understand what's wrong with assigning the value 0.1 to a float variable .

There's nothing wrong with it, the compiler is warning you that you are trying to assign a double to a float.
A literal 0.1 is a double in your compiler.
Do a test. Add these printf(s) to your snippet.

printf( "sizeof of 0.1 = %d bytes\n", sizeof( 0.1 ) );
printf( "sizeof of float = %d bytes\n", sizeof( float ) );

The result will be clear to you.

[Edit]: Some extra.

In fact even

if( a <= 0.1 )

will evaluate to FALSE because float != double. However

if( a <= ( float ) 0.1 )

will evaluate to TRUE

commented: Very helpful +2

This helped a lot , thanks Aia . You're great .

Very interesting case
If you change 0.1 to 0.5 you will not get warning message

int main()
{
    float a;
    a=0.5; 

    if(a<0.5)
    { 
        printf("C\n");
    }
    else
    {
        printf("C++\n");
    }
}

You could also initialize a float using

float a = 0.1f;

The f tells the compiler that its a float.

On related topic, you may find this thread interesting.
ArkM has explained floating pont conversions pretty well.

Oops, replied to a solved thread. :icon_cheesygrin:

I know that this thread is a year old but I just hod to comment.

I am just trying to learn C++ on my owna nd picked up a book. One of the examples in the book for building your own structures is as follows:

//structur.cpp -- a simple sructure
#include<iostream>
struct inflatable //structure declaration
{
	char name[20];
	float volume;
	double price;
};

int main()
{
	using namespace std;
	inflatable guest =
	{
		"Glorious Gloria",  //name value
		1.88,  //volume value
		29.99  //price value
	};  //guest is a structure variable of the type inflatable
// its initialized to the indicated values

this gave me the exact same compile errors posted here. So I googled the error and was brought here. From this thread I attempted to change the code by adding the "f" to show the value is a float and it worked! Thanks guys!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.