Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 916
deontologician Avatar asked Jun 28 '11 22:06

deontologician


People also ask

Does C have type inference?

When we declare a variable in C, it is necessary that a type is explicitly associated to it (e.g., int or double ). This is a distinction to languages that feature a so-called type inference, where programmers are freed from the need of annotating types.

What languages have type inference?

Some languages that include type inference include C++11, C# (starting with version 3.0), Chapel, Clean, Crystal, D, F#, FreeBASIC, Go, Haskell, Java (starting with version 10), Julia, Kotlin, ML, Nim, OCaml, Opa, Q#, RPython, Rust, Scala, Swift, TypeScript, Vala, Dart, and Visual Basic (starting with version 9.0).

What is type inference in programming?

Type inference is the automatic deduction of the data types of specific expressions in a programming language, usually done at compile time.

Does Python use type inference?

Python doesn't do static type inference, because it wants to let you do things that are impossible under such a scheme.


1 Answers

GCC 5.1 supports:

  • __auto_type extension, analogous C++11 auto
  • typeof extension, analogous to C++11 decltype

    /* Same as: double j = 0.5; */
    typeof(1 + 0.5) j = 0.5;
    assert(j == 0.5);
    

    Linux kernel example: How does the typecheck macro from the Linux kernel work?

  • _Generic C11 keyword: Syntax and Sample Usage of _Generic in C11

    __auto_type i = 1;
    assert(_Generic((i), int: 1, default: 0));