Search code examples
cfloating-pointprocessor

Code explanation and decimal comparison by processors


Recently I came across a program:

float a = 0.7;
if(a < 0.7)
  printf("Yes");
else
  printf("No");


I understood how the code prints Yes. But, isn't 0.7 on the right side of inequality same. Won't the binary value of 'a' and '0.7' be same in the memory?
Why is 0.7, used as 0.7 but variable 'a' has the value of less than that of 0.7, as there is not definite binary representation of 0.7?


Solution

  • I am glad you thought a step further regarding the program.
    Actually, the result you get is due to the change in data types of the variable 'a' and the value of '0.7'.

    The variable 'a' is of data type float, while '0.7' is of data type double. This is the default behaviour of decimal points. Double data type has double the precision than that of a float. In your code, if you replace the if condition with:

    if(a < 0.7f)
    


    The result will be different. Your program will give output "No" then. Another way of cross checking will be following line of code:

    printf("%d", sizeof(0.7));
    printf("%d", sizeof(a));
    


    In this case, the output will be 8 and 4 (This may vary). Coming to your question, none of them is stored as 0.7 in the main the memory of registers but, the decimal with double data type is more close to being 0.7