I am coding in Code::Blocks, in the C programming language:
#include <stdio.h>
int main() {
float var1 = 3.145926535897932;
double var2 = 3.145926535897932;
long double var3 = 3.14159265389793213456;
printf("%d\n", sizeof(float));
printf("%d\n", sizeof(double));
printf("%d\n", sizeof(long double));
printf("%.16f\n", var1);
printf("%.16f\n", var2);
printf("%.21Lf\n", var3);
return 0;
}
I am getting output as:-
4
8
16
3.1459264755249023
3.1459265358979320
0.000000000000000000000
Why am I getting 0.000000000000000000000 instead of 3.14159265389793213456, does my system does not support long double or is there a mistake in my code?
And if long double does not work in my system how it is able to give output of size of long double?
On my system (OS/X with clang), I get the expected output:
Yet the compiler produces many warnings:
Here are the explanations:
sizeofoperator has typesize_twhich is different fromint: you should either case it as(int)or use theprintfconversion specifier%zu.floatvalue should be initialized from afloatconstant:float var1 = 3.145926535897932F;long doublevalue should be initialized from along doubleconstant:long double var1 = 3.145926535897932L;printf("%.16f\n", var1),var1is implicitly converted to typedoubleas specified for variable arguments in vararg functions. You might make this conversion explicit to silence this warning, showing the behavior is expected.printf("%.21Lf\n", var3);conforms to the C99 Standard, but the C library on your system seems incompatible with the compiler in use regarding the typelong double.Microsoft decided more than 10 years ago to map type
long doubleto typedoublein their tools (cf Why did Microsoft abandon long double data type? ).The compiler you use on your system seems to handle
long doublein a different way that is incompatible with the C library your program links to. It is also possible that this library does not conform to the C99 specification, eg: the%Ldconversion for typelong double, or uses a different ABI to passlong doublevalues. Older Microsoft C libraries are known to have such problems decades after the C Standard was published. You should try and upgrade the system or switch to a conformant C development system.Here is a modified version, that no longer has undefined behavior, but probably still won't produce the expected output on your system:
Output: