Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC gives incorrect answer with optimization enabled

Tags:

c

gcc

I have the following C program

double d = 1.4;
int x;
x = d * 10;
printf("\n\n VALUE = %d " ,x);

I have gcc 4.3.3 which comes with Ubuntu 9.04

I get answer as 13 with -O0 but get correct answer i.e 14 with higher levels of optimization

Is this a known issue or something wrong with my code?

like image 502
user555850 Avatar asked Dec 28 '10 10:12

user555850


2 Answers

You can't represent 1.4 exactly using double, the value is actually a bit lagrer or a bit smaller (see this). So there is no "correct" answer - use round() instead of implictly truncating.

like image 151
crazylammer Avatar answered Oct 05 '22 12:10

crazylammer


This is gcc bug #323 , in reality this is not a bug but an implementation detail.

like image 28
ismail Avatar answered Oct 05 '22 13:10

ismail