Assign double constant to float variable without warning in C?

In the C programming language, the floating-point constant is a double type by default

therefore 3.1415 is a double type unless the suffix 'f' or 'F' is used to indicate a float type.

I assume that const float pi = 3.1415 will raise a warning, but not really.

when I try to use them under gcc using -Wall:

 float f = 3.1415926; double d = 3.1415926; printf("f: %f\n", f); printf("d: %f\n", d); f = 3.1415926f; printf("f: %f\n", f); int i = 3.1415926; printf("i: %d\n", i); 

result:

 f: 3.141593 d: 3.141593 f: 3.141593 i: 3 

the result (including the double variable) obviously loses accuracy, but compiles without warning.
so what did the compiler do with this? or didn’t I understand something?

+6
source share
3 answers

-Wall does not include warnings about loss of accuracy, truncation of values, etc., because these warnings are annoying noise, and "fixing them" requires cluttering up the correct code with a bunch of ugly throws. If you need warnings of this nature, you need to explicitly enable them.

In addition, the use of printf has nothing to do with the accuracy of the actual variables, but only the exact printing of printf , by default - 6 places after the decimal point.

+7
source

%f can be used with float and double . If you want to use more accurately

 printf("f: %.16f",d); 

And here's what happens under the hood:

 float f = 3.1415926; // The double 3.1415926 is truncated to float double d = 3.1415926; printf("f: %f\n", f); printf("d: %f\n", d); f = 3.1415926f; // Float is specified printf("f: %f\n", f); int i = 3.1415926; // Truncation from double to int printf("i: %d\n", i); 
+2
source

If you want warnings for this, I believe that -Wconversion places them in mainline gcc-4.3 and later.

If you use OS X, put them in Apple GCC using gcc-4.0.1. I believe that clang is consistent with basic gcc behavior.

+1
source

Source: https://habr.com/ru/post/891749/


All Articles