In case of long double x = 8.99999999999999999
, the value is stored as double
since ' L ' is not appended. Why can't the C compiler do type inference when I have already declared the variable x
to be a long double
float type?
The C compiler doesn't do type inference because C is not type safe. You can easily cast things willie nilly to void, void pointers, and back again. It's not against the rules. This implies, at the very least, that any sort of type inference for C would be only approximate, and that at best you'd have the compiler giving you clues as to what went wrong with your types.
As to why C doesn't do type inference: types in C are not intended to enforce logical relationships, or encode truth in the language. At some level, languages with sound type systems (Haskell, OCaml, SML, Coq, etc...) intend that the types tell you something: there's a theorem you can write down about your program from the types. (See Philip Wadler's "Theorem's for Free!" work for an interesting example of this!)
So why does C use types? The reason is purely that the compiler needs to know -- at some level -- how to organize your data as it is stored in memory. Instead of logical consistency, types in C are meat to tell you how things are laid out, where should I put this int within a structure, etc...
Instead, C has a number of idioms to emulate more standard features in type safe languages. For example, void pointers are usually used to represent parametric polymorphism. (So for example, you could have a list which can contain pointers to any data type.) In fact, it does something more, in C you can encode lists which point to different data types. While in traditional functional languages the inductive types for lists require all elements to be of the same type, you can in C easily encode inersection types and rows (this is done, in C, by tagging list elements with an identifier, for example).
There are type and memory safe dialects of C, see Cyclone as an example, where in some places, polymorphism does replace occurrences of things like void pointers while still giving you many of the niceties of the C language.