deontologician deontologician - 1 month ago 9
C Question

Would it be possible to add type inference to the C language?

Let's say, we create a reimplementation of C, with the only difference being
that types are inferred. Storage classes and modifiers would still need to be
given (const, static, restrict etc), and let's restrict our attention to single
file C programs for the moment. Could it be done? What are the major
impediments?

Some thoughts on what might cause problems with type inference


  • structs with the same field name would need to be disambiguated manually

  • same for unions with the same field names

  • casts would probably need a "from" annotation, something like

    var i = (uint32_t -> uint64_t) *some_pointer;



These problems would require a bit of user annotation, but shouldn't be too
burdensome, is there some killer issue that blows this idea out of the water?

Edit: To clarify, I'm not talking about adding generics or parametric polymorphism, just type inference for existing C types.

Edit 2014: Anyone interested in this concept may want to look into Rust

Answer

C promotes some types automatically, which complicates things. But to be workable, you need to have a couple additional differences from C as it exists: right now, the standard still supports to some extent legacy K&R C programs, and that requires that unspecified types be handled in particular ways. (See, for example, the rules for function parameters in the absence of prototypes. It also used to be possible to specify functions and variables with no type, and they would be defaulted to (int). (How for variables? Storage class only. static foo;)) All of this legacy type handling would have to be removed before a new implied types mechanism could be added.

Comments